From cc684fd3aada0163c61ac062ee8d90b6b7183e21 Mon Sep 17 00:00:00 2001 From: Markus Vahlenkamp Date: Fri, 20 Nov 2026 14:03:50 +0100 Subject: [PATCH 1/7] feat(schema): wire mutate_on_write schema contract into data-server Wire updated sdc-protos and schema-server local module replacements and verify SchemaElem.IsMutateOnWrite() through the local schema client for sdcio/data-server#550. Signed-off-by: Markus Vahlenkamp --- go.mod | 9 +- go.sum | 12 +- pkg/schema/local_mutate_on_write_test.go | 140 +++++++++++++++++++++++ 3 files changed, 151 insertions(+), 10 deletions(-) create mode 100644 pkg/schema/local_mutate_on_write_test.go diff --git a/go.mod b/go.mod index 16a197b1..b387ce3e 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,11 @@ go 1.26.0 replace github.com/openconfig/goyang v1.6.3 => github.com/sdcio/goyang v1.6.2-2 +replace ( + github.com/sdcio/schema-server => ../schema-server + github.com/sdcio/sdc-protos => ../sdc-protos +) + require ( github.com/AlekSi/pointer v1.2.0 github.com/beevik/etree v1.8.1 @@ -46,7 +51,7 @@ require ( github.com/clipperhouse/uax29/v2 v2.6.0 // indirect github.com/creack/pty v1.1.24 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/dgraph-io/badger/v4 v4.9.2 // indirect + github.com/dgraph-io/badger/v4 v4.9.6 // indirect github.com/dgraph-io/ristretto/v2 v2.4.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/emicklei/go-restful/v3 v3.12.1 // indirect @@ -86,7 +91,7 @@ require ( github.com/prometheus/common v0.72.0 // indirect github.com/prometheus/procfs v0.22.0 // indirect github.com/sirikothe/gotextfsm v1.0.1-0.20200816110946-6aa2cfd355e4 // indirect - github.com/sirupsen/logrus v1.9.4 // indirect + github.com/sirupsen/logrus v1.10.0 // indirect github.com/x448/float16 v0.8.4 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/otel v1.45.0 // indirect diff --git a/go.sum b/go.sum index 7c3c354c..84bf726d 100644 --- a/go.sum +++ b/go.sum @@ -27,8 +27,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dgraph-io/badger/v4 v4.9.2 h1:Wb5qw8gElqwV1a8msHTeQKova9b1V10heFKMIiPd80E= -github.com/dgraph-io/badger/v4 v4.9.2/go.mod h1:nJjaJTUOSsQEBhsq209FmwCvMJzEA3e74RjZw6V2pQI= +github.com/dgraph-io/badger/v4 v4.9.6 h1:IQqMPVGLNCQr1b4Mu8lHkYm/xyqFRsyKaFEtyLi9CCQ= +github.com/dgraph-io/badger/v4 v4.9.6/go.mod h1:Xa9dAupjbwAacupWFCpa6YEn9E1PjBXkfZYr2I/8aWg= github.com/dgraph-io/ristretto/v2 v2.4.0 h1:I/w09yLjhdcVD2QV192UJcq8dPBaAJb9pOuMyNy0XlU= github.com/dgraph-io/ristretto/v2 v2.4.0/go.mod h1:0KsrXtXvnv0EqnzyowllbVJB8yBonswa2lTCK2gGo9E= github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da h1:aIftn67I1fkbMa512G+w+Pxci9hJPB8oMnkcP3iZF38= @@ -189,17 +189,13 @@ github.com/sdcio/goyang v1.6.2-2 h1:qfeUKBmoKpiKAruuEc3+V8wgHKP/n1jRDEnTy23knV8= github.com/sdcio/goyang v1.6.2-2/go.mod h1:5WolITjek1NF8yrNERyVZ7jqjOClJTpO8p/+OwmETM4= github.com/sdcio/logger v0.0.3 h1:IFUbObObGry+S8lHGwOQKKRxJSuOphgRU/hxVhOdMOM= github.com/sdcio/logger v0.0.3/go.mod h1:yWaOxK/G6vszjg8tKZiMqiEjlZouHsjFME4zSk+SAEA= -github.com/sdcio/schema-server v0.0.34 h1:NNDOkvtUMONtBA7cVvN96F+FWGD/Do6HNqfchy9B8eI= -github.com/sdcio/schema-server v0.0.34/go.mod h1:6t8HLXpqUqEJmE5yNZh29u/KZw0jlOICdNWns7zE4GE= -github.com/sdcio/sdc-protos v0.0.56 h1:8tEbo53/2KAd/5mruqiKhNsDljKcWI6nhCfriYE2SvE= -github.com/sdcio/sdc-protos v0.0.56/go.mod h1:hER0riYU3G55NnMQ0p0R9kIL/fzqq1zab4pOgUT3Yfg= github.com/sdcio/yang-parser v0.0.12 h1:RSSeqfAOIsJx5Lno5u4/ezyOmQYUduQ22rBfU/mtpJ4= github.com/sdcio/yang-parser v0.0.12/go.mod h1:CBqn3Miq85qmFVGHxHXHLluXkaIOsTzV06IM4DW6+D4= github.com/sirikothe/gotextfsm v1.0.1-0.20200816110946-6aa2cfd355e4 h1:FHUL2HofYJuslFOQdy/JjjP36zxqIpd/dcoiwLMIs7k= github.com/sirikothe/gotextfsm v1.0.1-0.20200816110946-6aa2cfd355e4/go.mod h1:CJYqpTg9u5VPCoD0VEl9E68prCIiWQD8m457k098DdQ= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= -github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= -github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= +github.com/sirupsen/logrus v1.10.0 h1:T8MxJJXVZkfcC5zSRMRAg2F8+lxjmUCGGWPzFxO+Msc= +github.com/sirupsen/logrus v1.10.0/go.mod h1:FXZFonkDAnFozmO+5hGAFvB0Yg9/j2SIhA/QuIkP180= github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= diff --git a/pkg/schema/local_mutate_on_write_test.go b/pkg/schema/local_mutate_on_write_test.go new file mode 100644 index 00000000..bad25e7f --- /dev/null +++ b/pkg/schema/local_mutate_on_write_test.go @@ -0,0 +1,140 @@ +// Copyright 2024 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema_test + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/sdcio/data-server/pkg/schema" + "github.com/sdcio/schema-server/pkg/store/memstore" + sdcpb "github.com/sdcio/sdc-protos/sdcpb" +) + +func TestLocalClient_GetSchema_IsMutateOnWrite(t *testing.T) { + yangDir := t.TempDir() + + files := map[string]string{ + "sdcio-ext.yang": `module sdcio-ext { + yang-version 1.1; + namespace "urn:sdcio-ext"; + prefix "sdcio-ext"; + extension mutate-on-write; +} +`, + "iana-crypt-hash.yang": `module iana-crypt-hash { + namespace "urn:ietf:params:xml:ns:yang:iana-crypt-hash"; + prefix "ianach"; + typedef crypt-hash { + type string; + } +} +`, + "device.yang": `module ds-mow-test { + yang-version 1.1; + namespace "urn:ds:mow:test"; + prefix "dsmow"; + + import iana-crypt-hash { prefix "ianach"; } + + container system { + leaf hashed-password { + type ianach:crypt-hash; + } + leaf overlay-password { + type string; + } + leaf hostname { + type string; + } + } +} +`, + "overlay.yang": `module ds-mow-overlay { + yang-version 1.1; + namespace "urn:ds:mow:overlay"; + prefix "dsov"; + + import ds-mow-test { prefix "dsmow"; } + import sdcio-ext { prefix "mowext"; } + + deviation /dsmow:system/dsmow:overlay-password { + deviate add { + mowext:mutate-on-write; + } + } +} +`, + } + + for name, content := range files { + if err := os.WriteFile(filepath.Join(yangDir, name), []byte(content), 0o600); err != nil { + t.Fatalf("write %s: %v", name, err) + } + } + + ctx := context.Background() + st := memstore.New() + t.Cleanup(func() { _ = st.Close() }) + + client := schema.NewLocalClient(st) + scRef := &sdcpb.Schema{ + Name: "ds-mow", + Vendor: "test", + Version: "1.0.0", + } + + if _, err := client.CreateSchema(ctx, &sdcpb.CreateSchemaRequest{ + Schema: scRef, + File: []string{yangDir}, + }); err != nil { + t.Fatalf("CreateSchema: %v", err) + } + + tests := []struct { + name string + elems []string + want bool + }{ + {name: "container returns false", elems: []string{"system"}, want: false}, + {name: "iana-crypt-hash leaf returns true", elems: []string{"system", "hashed-password"}, want: true}, + {name: "custom-prefix deviate add overlay leaf returns true", elems: []string{"system", "overlay-password"}, want: true}, + {name: "plain string hostname returns false", elems: []string{"system", "hostname"}, want: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + toPathRsp, err := client.ToPath(ctx, &sdcpb.ToPathRequest{ + Schema: scRef, + PathElement: tt.elems, + }) + if err != nil { + t.Fatalf("ToPath(%v): %v", tt.elems, err) + } + rsp, err := client.GetSchema(ctx, &sdcpb.GetSchemaRequest{ + Schema: scRef, + Path: toPathRsp.GetPath(), + }) + if err != nil { + t.Fatalf("GetSchema(%v): %v", tt.elems, err) + } + if got := rsp.GetSchema().IsMutateOnWrite(); got != tt.want { + t.Errorf("GetSchema(%v).IsMutateOnWrite() = %v, want %v", tt.elems, got, tt.want) + } + }) + } +} From 489a149e27f36046e72ca4201dad909ce77ecc72 Mon Sep 17 00:00:00 2001 From: Markus Vahlenkamp Date: Fri, 20 Nov 2026 16:56:15 +0100 Subject: [PATCH 2/7] feat(datastore,tree): add post-Set readback and confirmed baselines for TransactionSet Capture targeted post-Set CONFIG readbacks for schema-flagged mutate-on-write leaves strictly in memory as confirmed applied values keyed by canonical path, winning owner, and intended value, update Running with the target readback value, and evaluate tree running-equality diffing, NOT_APPLIED deviations, and BlameConfig against that baseline while preserving authored values on northbound reads and validation for sdcio/data-server#550. Signed-off-by: Markus Vahlenkamp --- pkg/datastore/confirmed_applied_values.go | 203 +++ pkg/datastore/datastore_rpc.go | 11 +- pkg/datastore/mutate_on_write_test.go | 1264 +++++++++++++++++ pkg/datastore/post_set_readback.go | 194 +++ pkg/datastore/sync.go | 2 +- pkg/datastore/transaction_rpc.go | 17 +- pkg/tree/api/leaf_variants.go | 34 +- pkg/tree/api/tree_context.go | 10 + pkg/tree/confirmed_applied_value_test.go | 276 ++++ .../ops/validation/validation_dispatch.go | 9 + .../ops/validation/validation_entry_length.go | 2 +- .../ops/validation/validation_entry_must.go | 6 + .../validation/validation_entry_pattern.go | 2 +- .../ops/validation/validation_entry_range.go | 2 +- pkg/tree/processors/processor_blame_config.go | 14 +- pkg/tree/tree_context.go | 42 +- pkg/utils/converter.go | 85 +- pkg/utils/testhelper/utils.go | 19 + 18 files changed, 2117 insertions(+), 75 deletions(-) create mode 100644 pkg/datastore/confirmed_applied_values.go create mode 100644 pkg/datastore/mutate_on_write_test.go create mode 100644 pkg/datastore/post_set_readback.go create mode 100644 pkg/tree/confirmed_applied_value_test.go diff --git a/pkg/datastore/confirmed_applied_values.go b/pkg/datastore/confirmed_applied_values.go new file mode 100644 index 00000000..6ea12e9d --- /dev/null +++ b/pkg/datastore/confirmed_applied_values.go @@ -0,0 +1,203 @@ +// Copyright 2024 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package datastore + +import ( + "slices" + "strings" + "sync" + + "github.com/sdcio/data-server/pkg/tree/api" + sdcpb "github.com/sdcio/sdc-protos/sdcpb" + "google.golang.org/protobuf/proto" +) + +// canonicalLeafPath is the module-prefix-stripped, sorted-key path identifier +// shared across tree lookups and southbound readbacks. +type canonicalLeafPath string + +type confirmedAppliedEntry struct { + owner string + intendedValue *sdcpb.TypedValue + confirmedValue *sdcpb.TypedValue +} + +// confirmedAppliedValues holds the datastore's in-memory drift baselines for +// mutate-on-write leaves, keyed by canonicalLeafPath and bound to (owner, intendedValue). +// Entries live strictly in process memory and are never written to cache storage. +type confirmedAppliedValues struct { + mu sync.RWMutex + entries map[canonicalLeafPath]confirmedAppliedEntry +} + +func newConfirmedAppliedValues() *confirmedAppliedValues { + return &confirmedAppliedValues{ + entries: make(map[canonicalLeafPath]confirmedAppliedEntry), + } +} + +// Lookup returns a copy of the confirmed applied value only when path, winningOwner, +// and intendedValue all match the stored baseline. +func (s *confirmedAppliedValues) Lookup(path *sdcpb.Path, winningOwner string, intendedValue *sdcpb.TypedValue) *sdcpb.TypedValue { + if s == nil || path == nil || winningOwner == "" || intendedValue == nil { + return nil + } + key := newCanonicalLeafPath(path) + + s.mu.RLock() + entry, ok := s.entries[key] + s.mu.RUnlock() + if !ok { + return nil + } + if entry.owner != winningOwner || !api.TypedValuesEqual(entry.intendedValue, intendedValue) { + return nil + } + return proto.Clone(entry.confirmedValue).(*sdcpb.TypedValue) +} + +// Record stores confirmedValue as the baseline for (path, owner, intendedValue) +// when confirmedValue is a non-empty leaf value. +func (s *confirmedAppliedValues) Record(path *sdcpb.Path, owner string, intendedValue, confirmedValue *sdcpb.TypedValue) { + if s == nil || path == nil || owner == "" || intendedValue == nil || !isNonEmptyTypedValue(confirmedValue) { + return + } + key := newCanonicalLeafPath(path) + + s.mu.Lock() + s.entries[key] = confirmedAppliedEntry{ + owner: owner, + intendedValue: proto.Clone(intendedValue).(*sdcpb.TypedValue), + confirmedValue: proto.Clone(confirmedValue).(*sdcpb.TypedValue), + } + s.mu.Unlock() +} + +// Delete removes any stored baseline for path. +func (s *confirmedAppliedValues) Delete(path *sdcpb.Path) { + if s == nil || path == nil { + return + } + key := newCanonicalLeafPath(path) + s.mu.Lock() + delete(s.entries, key) + s.mu.Unlock() +} + +// ClearAll removes all stored baselines. +func (s *confirmedAppliedValues) ClearAll() { + if s == nil { + return + } + s.mu.Lock() + clear(s.entries) + s.mu.Unlock() +} + +var _ api.ConfirmedAppliedValueResolver = (*confirmedAppliedValues)(nil) + +func stripModulePrefix(name string) string { + if _, local, ok := strings.Cut(name, ":"); ok { + return local + } + return name +} + +func canonicalPath(p *sdcpb.Path) *sdcpb.Path { + if p == nil { + return &sdcpb.Path{IsRootBased: true} + } + elems := make([]*sdcpb.PathElem, 0, len(p.GetElem())) + for _, pe := range p.GetElem() { + var keys map[string]string + if len(pe.GetKey()) > 0 { + keys = make(map[string]string, len(pe.GetKey())) + for k, v := range pe.GetKey() { + keys[stripModulePrefix(k)] = v + } + } + elems = append(elems, sdcpb.NewPathElem(stripModulePrefix(pe.GetName()), keys)) + } + return &sdcpb.Path{ + IsRootBased: true, + Elem: elems, + } +} + +var keyValEscaper = strings.NewReplacer(`\`, `\\`, `]`, `\]`) + +func newCanonicalLeafPath(p *sdcpb.Path) canonicalLeafPath { + if p == nil || len(p.GetElem()) == 0 { + return "/" + } + var sb strings.Builder + for _, pe := range p.GetElem() { + sb.WriteByte('/') + sb.WriteString(stripModulePrefix(pe.GetName())) + if kv := pe.GetKey(); len(kv) > 0 { + normalized := make(map[string]string, len(kv)) + keys := make([]string, 0, len(kv)) + for k, v := range kv { + nk := stripModulePrefix(k) + normalized[nk] = v + keys = append(keys, nk) + } + slices.Sort(keys) + for _, k := range keys { + sb.WriteByte('[') + sb.WriteString(k) + sb.WriteByte('=') + sb.WriteString(keyValEscaper.Replace(normalized[k])) + sb.WriteByte(']') + } + } + } + return canonicalLeafPath(sb.String()) +} + +// isNonEmptyTypedValue reports whether tv is a non-empty scalar or leaf-list +// TypedValue suitable for a confirmed applied value. Unexpanded JSON envelopes +// are rejected so baselines always store schema-typed leaf values. +func isNonEmptyTypedValue(tv *sdcpb.TypedValue) bool { + if tv == nil || tv.GetValue() == nil { + return false + } + switch v := tv.GetValue().(type) { + case *sdcpb.TypedValue_StringVal: + return v.StringVal != "" + case *sdcpb.TypedValue_AsciiVal: + return v.AsciiVal != "" + case *sdcpb.TypedValue_BytesVal: + return len(v.BytesVal) > 0 + case *sdcpb.TypedValue_ProtoBytes: + return len(v.ProtoBytes) > 0 + case *sdcpb.TypedValue_AnyVal: + return v.AnyVal != nil && len(v.AnyVal.GetValue()) > 0 + case *sdcpb.TypedValue_JsonVal, *sdcpb.TypedValue_JsonIetfVal: + return false + case *sdcpb.TypedValue_LeaflistVal: + if v.LeaflistVal == nil || len(v.LeaflistVal.GetElement()) == 0 { + return false + } + for _, elem := range v.LeaflistVal.GetElement() { + if !isNonEmptyTypedValue(elem) { + return false + } + } + return true + default: + return true + } +} diff --git a/pkg/datastore/datastore_rpc.go b/pkg/datastore/datastore_rpc.go index ca8b4c8e..d1c98d3b 100644 --- a/pkg/datastore/datastore_rpc.go +++ b/pkg/datastore/datastore_rpc.go @@ -73,6 +73,8 @@ type Datastore struct { syncTree *tree.RootEntry syncTreeMutex *sync.RWMutex + confirmedApplied *confirmedAppliedValues + taskPool *pool.SharedTaskPool } @@ -98,7 +100,8 @@ func New(ctx context.Context, c *config.DatastoreConfig, sc schema.Client, cc ca ) scb := schemaClient.NewSchemaClientBound(c.Schema, sc) - tc := tree.NewTreeContext(scb, pool.NewSharedTaskPool(ctx, runtime.GOMAXPROCS(0))) + confirmed := newConfirmedAppliedValues() + tc := tree.NewTreeContext(scb, pool.NewSharedTaskPool(ctx, runtime.GOMAXPROCS(0)), tree.WithConfirmedAppliedValues(confirmed)) syncTreeRoot, err := tree.NewTreeRoot(ctx, tc) if err != nil { cancel() @@ -118,6 +121,7 @@ func New(ctx context.Context, c *config.DatastoreConfig, sc schema.Client, cc ca deviationClients: make(map[sdcpb.DataServer_WatchDeviationsServer]string), syncTree: syncTreeRoot, syncTreeMutex: &sync.RWMutex{}, + confirmedApplied: confirmed, taskPool: pool.NewSharedTaskPool(ctx, runtime.GOMAXPROCS(0)), } ds.transactionManager = types.NewTransactionManager(NewDatastoreRollbackAdapter(ds), types.WithAutoRollbackLock(ds.dmutex)) @@ -271,11 +275,14 @@ func (d *Datastore) Stop(ctx context.Context) error { return nil } +func (d *Datastore) newTreeContext() *tree.TreeContext { + return tree.NewTreeContext(d.schemaClient, d.taskPool, tree.WithConfirmedAppliedValues(d.confirmedApplied)) +} + func (d *Datastore) BlameConfig(ctx context.Context, includeDefaults bool) (*sdcpb.BlameTreeElement, error) { log := logf.FromContext(ctx).WithName("BlameConfig") ctx = logf.IntoContext(ctx, log) - // create a new TreeRoot by copying the syncTree d.syncTreeMutex.RLock() root, err := d.syncTree.DeepCopy(ctx) d.syncTreeMutex.RUnlock() diff --git a/pkg/datastore/mutate_on_write_test.go b/pkg/datastore/mutate_on_write_test.go new file mode 100644 index 00000000..946d2117 --- /dev/null +++ b/pkg/datastore/mutate_on_write_test.go @@ -0,0 +1,1264 @@ +// Copyright 2024 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package datastore + +import ( + "context" + "encoding/json" + "errors" + "net" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" + "time" + + cacheconfig "github.com/sdcio/cache/pkg/config" + "github.com/sdcio/data-server/mocks/mocktarget" + "github.com/sdcio/data-server/pkg/cache" + "github.com/sdcio/data-server/pkg/config" + schemaClient "github.com/sdcio/data-server/pkg/datastore/clients/schema" + targettypes "github.com/sdcio/data-server/pkg/datastore/target/types" + "github.com/sdcio/data-server/pkg/datastore/types" + "github.com/sdcio/data-server/pkg/pool" + "github.com/sdcio/data-server/pkg/schema" + "github.com/sdcio/data-server/pkg/tree" + "github.com/sdcio/data-server/pkg/tree/consts" + jsonImporter "github.com/sdcio/data-server/pkg/tree/importer/json" + "github.com/sdcio/data-server/pkg/utils/testhelper" + "github.com/sdcio/schema-server/pkg/store/memstore" + sdcpb "github.com/sdcio/sdc-protos/sdcpb" + "go.uber.org/mock/gomock" + "google.golang.org/grpc" + "google.golang.org/grpc/peer" +) + +type mowDatastoreFixture struct { + ds *Datastore + sbi *mocktarget.MockTarget + localCache cache.Client + schema *sdcpb.Schema +} + +func initMutateOnWriteSchema(t *testing.T) (schema.Client, *config.SchemaConfig) { + t.Helper() + yangDir := t.TempDir() + + files := map[string]string{ + "sdcio-ext.yang": `module sdcio-ext { + yang-version 1.1; + namespace "urn:sdcio-ext"; + prefix "sdcio-ext"; + extension mutate-on-write; +} +`, + "iana-crypt-hash.yang": `module iana-crypt-hash { + namespace "urn:ietf:params:xml:ns:yang:iana-crypt-hash"; + prefix "ianach"; + typedef crypt-hash { + type string; + } +} +`, + "device.yang": `module ds-mow-test { + yang-version 1.1; + namespace "urn:ds:mow:test"; + prefix "dsmow"; + + import iana-crypt-hash { prefix "ianach"; } + + container system { + leaf hashed-password { + type ianach:crypt-hash; + } + leaf overlay-password { + type string { + length "8..128"; + } + must "string-length(.) <= 32" { + error-message "cleartext overlay-password must be at most 32 chars"; + } + } + leaf-list hashed-key { + type ianach:crypt-hash; + } + leaf hostname { + type string; + } + list user { + key "username"; + leaf username { + type string; + } + leaf password { + type ianach:crypt-hash; + } + } + } +} +`, + "overlay.yang": `module ds-mow-overlay { + yang-version 1.1; + namespace "urn:ds:mow:overlay"; + prefix "dsov"; + + import ds-mow-test { prefix "dsmow"; } + import sdcio-ext { prefix "mowext"; } + + deviation /dsmow:system/dsmow:overlay-password { + deviate add { + mowext:mutate-on-write; + } + } +} +`, + } + + for name, content := range files { + if err := os.WriteFile(filepath.Join(yangDir, name), []byte(content), 0o600); err != nil { + t.Fatalf("write %s: %v", name, err) + } + } + + st := memstore.New() + t.Cleanup(func() { _ = st.Close() }) + + sc := schema.NewLocalClient(st) + scRef := &sdcpb.Schema{ + Name: "ds-mow", + Vendor: "test", + Version: "1.0.0", + } + if _, err := sc.CreateSchema(context.Background(), &sdcpb.CreateSchemaRequest{ + Schema: scRef, + File: []string{yangDir}, + }); err != nil { + t.Fatalf("CreateSchema: %v", err) + } + + return sc, &config.SchemaConfig{ + Name: scRef.Name, + Vendor: scRef.Vendor, + Version: scRef.Version, + } +} + +func newMOWDatastoreFixture(t *testing.T, ctrl *gomock.Controller) *mowDatastoreFixture { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + + sc, schemaCfg := initMutateOnWriteSchema(t) + scb := schemaClient.NewSchemaClientBound(schemaCfg, sc) + + localCache, err := cache.NewLocalCache(&cacheconfig.CacheConfig{Dir: t.TempDir()}) + if err != nil { + t.Fatalf("NewLocalCache: %v", err) + } + const dsName = "mow-ds" + if err := localCache.InstanceCreate(ctx, dsName); err != nil { + t.Fatalf("InstanceCreate: %v", err) + } + ccb := cache.NewCacheClientBound(dsName, localCache) + + vpf := pool.NewSharedTaskPool(ctx, runtime.GOMAXPROCS(0)) + confirmed := newConfirmedAppliedValues() + tc := tree.NewTreeContext(scb, vpf, tree.WithConfirmedAppliedValues(confirmed)) + syncTreeRoot, err := tree.NewTreeRoot(ctx, tc) + if err != nil { + t.Fatalf("NewTreeRoot: %v", err) + } + if err := syncTreeRoot.FinishInsertionPhase(ctx); err != nil { + t.Fatalf("FinishInsertionPhase: %v", err) + } + + sbi := mocktarget.NewMockTarget(ctrl) + ds := &Datastore{ + config: &config.DatastoreConfig{ + Name: dsName, + Schema: schemaCfg, + Validation: config.NewValidationConfig(), + SBI: &config.SBI{Type: "gnmi", GnmiOptions: &config.SBIGnmiOptions{Encoding: "JSON_IETF"}}, + }, + cacheClient: ccb, + sbi: sbi, + schemaClient: scb, + ctx: ctx, + cfn: cancel, + m: &sync.RWMutex{}, + deviationClients: make(map[sdcpb.DataServer_WatchDeviationsServer]string), + dmutex: &sync.Mutex{}, + syncTree: syncTreeRoot, + syncTreeMutex: &sync.RWMutex{}, + confirmedApplied: confirmed, + taskPool: vpf, + } + ds.transactionManager = types.NewTransactionManager(NewDatastoreRollbackAdapter(ds), types.WithAutoRollbackLock(ds.dmutex)) + + return &mowDatastoreFixture{ + ds: ds, + sbi: sbi, + localCache: localCache, + schema: &sdcpb.Schema{ + Name: schemaCfg.Name, + Vendor: schemaCfg.Vendor, + Version: schemaCfg.Version, + }, + } +} + +func buildJSONIntent(t *testing.T, ds *Datastore, name string, prio int32, nonRevertive bool, payload map[string]any) *types.TransactionIntent { + t.Helper() + raw, err := json.Marshal(payload) + if err != nil { + t.Fatalf("marshal payload: %v", err) + } + ti, err := ds.SdcpbTransactionIntentToInternalTI(context.Background(), &sdcpb.TransactionIntent{ + Intent: name, + Priority: prio, + NonRevertive: nonRevertive, + Update: []*sdcpb.Update{{ + Path: &sdcpb.Path{}, + Value: &sdcpb.TypedValue{ + Value: &sdcpb.TypedValue_JsonIetfVal{JsonIetfVal: raw}, + }, + }}, + }) + if err != nil { + t.Fatalf("SdcpbTransactionIntentToInternalTI: %v", err) + } + return ti +} + +type fakeWatchDeviationStream struct { + grpc.ServerStream + ctx context.Context + mu sync.Mutex + events []*sdcpb.WatchDeviationResponse + doneCh chan struct{} + once sync.Once +} + +func newFakeWatchDeviationStream(ctx context.Context) *fakeWatchDeviationStream { + pCtx := peer.NewContext(ctx, &peer.Peer{ + Addr: &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 54321}, + }) + return &fakeWatchDeviationStream{ + ctx: pCtx, + doneCh: make(chan struct{}), + } +} + +func (f *fakeWatchDeviationStream) Context() context.Context { + return f.ctx +} + +func (f *fakeWatchDeviationStream) Send(resp *sdcpb.WatchDeviationResponse) error { + f.mu.Lock() + f.events = append(f.events, resp) + f.mu.Unlock() + if resp.GetEvent() == sdcpb.DeviationEvent_END { + f.once.Do(func() { close(f.doneCh) }) + } + return nil +} + +func collectWatchDeviationsBatch(t *testing.T, ds *Datastore) []*sdcpb.WatchDeviationResponse { + t.Helper() + mgrCtx, mgrCancel := context.WithCancel(context.Background()) + defer mgrCancel() + + stream := newFakeWatchDeviationStream(mgrCtx) + if err := ds.WatchDeviations(&sdcpb.WatchDeviationRequest{Name: []string{ds.Name()}}, stream); err != nil { + t.Fatalf("WatchDeviations: %v", err) + } + defer ds.StopDeviationsWatch(stream) + + done := make(chan struct{}) + go func() { + defer close(done) + ds.DeviationMgr(mgrCtx, &config.DeviationConfig{Interval: 5 * time.Millisecond}) + }() + + select { + case <-stream.doneCh: + case <-time.After(3 * time.Second): + t.Fatal("timed out waiting for WatchDeviations batch") + } + mgrCancel() + <-done + + stream.mu.Lock() + defer stream.mu.Unlock() + return append([]*sdcpb.WatchDeviationResponse(nil), stream.events...) +} + +func updatesByXPath(upds []*sdcpb.Update) map[string]string { + m := make(map[string]string, len(upds)) + for _, u := range upds { + p := u.GetPath().ToXPath(false) + if len(p) > 0 && p[0] != '/' { + p = "/" + p + } + m[p] = u.GetValue().ToString() + } + return m +} + +func expectEmptySet(t *testing.T, sbi *mocktarget.MockTarget) *gomock.Call { + t.Helper() + return sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + DoAndReturn(func(setCtx context.Context, source targettypes.TargetSource) (*sdcpb.SetDataResponse, error) { + upds, err := source.ToProtoUpdates(setCtx, true) + if err != nil { + return nil, err + } + dels, err := source.ToProtoDeletes(setCtx) + if err != nil { + return nil, err + } + if len(upds) != 0 || len(dels) != 0 { + t.Fatalf("expected empty southbound diff, got upds=%v dels=%v", upds, dels) + } + return &sdcpb.SetDataResponse{}, nil + }).Times(1) +} + +func TestConfirmedAppliedValues_CanonicalMultiKeyPrefixSorting(t *testing.T) { + store := newConfirmedAppliedValues() + prefixed := &sdcpb.Path{ + Origin: "openconfig", + IsRootBased: false, + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("zmod:acl", map[string]string{"zmod:a": "corpA:alice", "amod:b": "10.0.0.1:179"}), + sdcpb.NewPathElem("zmod:secret", nil), + }, + } + unprefixed := &sdcpb.Path{ + IsRootBased: true, + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("acl", map[string]string{"a": "corpA:alice", "b": "10.0.0.1:179"}), + sdcpb.NewPathElem("secret", nil), + }, + } + distinctColonKey := &sdcpb.Path{ + IsRootBased: true, + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("acl", map[string]string{"a": "corpB:alice", "b": "10.0.0.1:179"}), + sdcpb.NewPathElem("secret", nil), + }, + } + intended := &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: "plain"}} + confirmed := &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: "$6$hash"}} + + store.Record(prefixed, "intent1", intended, confirmed) + got := store.Lookup(unprefixed, "intent1", intended) + if got == nil || got.GetStringVal() != "$6$hash" { + t.Fatalf("Lookup across inverted module-prefix multi-key path = %v, want $6$hash", got) + } + if collide := store.Lookup(distinctColonKey, "intent1", intended); collide != nil { + t.Fatalf("single-colon string key corpB:alice collided with corpA:alice: %v", collide) + } + if gotXPath := canonicalPath(prefixed).ToXPath(false); gotXPath != "/acl[a=corpA:alice][b=10.0.0.1:179]/secret" { + t.Fatalf("canonicalPath XPath = %q, want /acl[a=corpA:alice][b=10.0.0.1:179]/secret", gotXPath) + } +} + +func TestDatastore_MutateOnWrite_SingleCommitConvergenceAndReads(t *testing.T) { + for _, tc := range []struct { + name string + nonRevertive bool + }{ + {name: "revertive intent", nonRevertive: false}, + {name: "non-revertive intent", nonRevertive: true}, + } { + t.Run(tc.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + const ( + cleartext = "MyS3cret!" + hashed = "$6$rounds=5000$saltsalt$hasheddigestvalue" + hostname = "leaf-router-01" + ) + + var pushedUpdates []*sdcpb.Update + setCall := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + DoAndReturn(func(setCtx context.Context, source targettypes.TargetSource) (*sdcpb.SetDataResponse, error) { + var err error + pushedUpdates, err = source.ToProtoUpdates(setCtx, true) + if err != nil { + return nil, err + } + return &sdcpb.SetDataResponse{}, nil + }).Times(1) + + f.sbi.EXPECT(). + Get(gomock.Any(), gomock.Any()). + After(setCall). + DoAndReturn(func(getCtx context.Context, req *sdcpb.GetDataRequest) (*sdcpb.GetDataResponse, error) { + if req.GetDataType() != sdcpb.DataType_CONFIG { + t.Errorf("Get DataType = %v, want %v", req.GetDataType(), sdcpb.DataType_CONFIG) + } + if len(req.GetPath()) != 1 { + t.Fatalf("expected targeted Get for 1 mutate-on-write path, got %d: %v", len(req.GetPath()), req.GetPath()) + } + gotPath := req.GetPath()[0].ToXPath(false) + if gotPath != "/system/hashed-password" && gotPath != "system/hashed-password" { + t.Errorf("targeted Get path = %q, want /system/hashed-password", gotPath) + } + + // Concurrent non-dryRun TransactionSet must fail fast while post-Set Get holds dmutex. + _, lockErr := f.ds.TransactionSet(context.Background(), "concurrent-tx", nil, nil, time.Minute, false) + if !errors.Is(lockErr, ErrDatastoreLocked) { + t.Errorf("concurrent TransactionSet during post-Set Get returned %v, want ErrDatastoreLocked", lockErr) + } + + return &sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{{ + Path: &sdcpb.Path{ + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("hashed-password", nil), + }, + }, + Value: &sdcpb.TypedValue{ + Value: &sdcpb.TypedValue_StringVal{StringVal: hashed}, + }, + }}, + }}, + }, nil + }).Times(1) + + intent := buildJSONIntent(t, f.ds, "intent1", 10, tc.nonRevertive, map[string]any{ + "system": map[string]any{ + "hashed-password": cleartext, + "hostname": hostname, + }, + }) + + resp, err := f.ds.TransactionSet(ctx, "tx-1", []*types.TransactionIntent{intent}, nil, time.Minute, false) + if err != nil { + t.Fatalf("TransactionSet: %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-1"); err != nil { + t.Fatalf("TransactionConfirm: %v", err) + } + + pushedMap := updatesByXPath(pushedUpdates) + if pushedMap["/system/hashed-password"] != cleartext || pushedMap["/system/hostname"] != hostname { + t.Fatalf("pushed southbound updates = %v, want cleartext %q and hostname %q", pushedMap, cleartext, hostname) + } + respMap := updatesByXPath(resp.GetUpdate()) + if respMap["/system/hashed-password"] != cleartext { + t.Fatalf("TransactionSetResponse update for hashed-password = %q, want %q", respMap["/system/hashed-password"], cleartext) + } + + namedResp, err := f.ds.GetIntent(ctx, "intent1") + if err != nil { + t.Fatalf("GetIntent(intent1): %v", err) + } + namedUpds, err := namedResp.ToProtoUpdates(ctx) + if err != nil { + t.Fatalf("namedResp.ToProtoUpdates: %v", err) + } + if got := updatesByXPath(namedUpds)["/system/hashed-password"]; got != cleartext { + t.Fatalf("GetIntent(intent1) hashed-password = %q, want authored %q", got, cleartext) + } + persistedBlob, err := f.localCache.InstanceIntentGet(ctx, f.ds.Name(), "intent1") + if err != nil { + t.Fatalf("InstanceIntentGet(intent1): %v", err) + } + if rawBlob := persistedBlob.String(); rawBlob == "" { + t.Fatal("expected non-empty persisted named intent blob") + } else if strings.Contains(rawBlob, hashed) { + t.Fatalf("persisted named intent blob leaked confirmed applied value %q: %s", hashed, rawBlob) + } + + runningResp, err := f.ds.GetIntent(ctx, consts.RunningIntentName) + if err != nil { + t.Fatalf("GetIntent(running): %v", err) + } + runningUpds, err := runningResp.ToProtoUpdates(ctx) + if err != nil { + t.Fatalf("runningResp.ToProtoUpdates: %v", err) + } + if got := updatesByXPath(runningUpds)["/system/hashed-password"]; got != hashed { + t.Fatalf("GetIntent(running) hashed-password = %q, want target readback %q", got, hashed) + } + + syncPayload := map[string]any{ + "system": map[string]any{ + "hashed-password": hashed, + "hostname": hostname, + }, + } + if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{}}, jsonImporter.NewJsonTreeImporter(syncPayload, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning: %v", err) + } + + events := collectWatchDeviationsBatch(t, f.ds) + for _, ev := range events { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + t.Fatalf("unexpected NOT_APPLIED deviation on converged mutate-on-write leaf: %v", ev) + } + } + + blame, err := f.ds.BlameConfig(ctx, false) + if err != nil { + t.Fatalf("BlameConfig: %v", err) + } + pwBlame := testhelper.FindBlameElement(blame, "system", "hashed-password") + if pwBlame == nil { + t.Fatalf("missing system/hashed-password in BlameConfig: %v", blame) + } + if pwBlame.GetOwner() != "intent1" || pwBlame.GetValue().GetStringVal() != cleartext { + t.Fatalf("BlameConfig owner/value = (%q, %v), want (%q, %q)", + pwBlame.GetOwner(), pwBlame.GetValue(), "intent1", cleartext) + } + if pwBlame.GetDeviationValue() != nil { + t.Fatalf("expected nil DeviationValue in BlameConfig, got %v", pwBlame.GetDeviationValue()) + } + }) + } +} + +func TestDatastore_MutateOnWrite_NonRepushValidationAndLeafList(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + const ( + pwCleartext = "AdminP@ss1" + pwHashed = "$6$rounds=5000$salt1$hash1" + overlayCleartext = "OverlaySecret1" // 14 chars (satisfies length 8..32) + overlayCipher = "$9$rounds=10000$longsaltvalue$ciphertext_much_longer_than_32_chars" // 66 chars (> 32-char YANG length limit) + ) + hashedKeys := []string{"$6$salt$keyhash1", "$6$salt$keyhash2"} + + set1 := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + + f.sbi.EXPECT(). + Get(gomock.Any(), gomock.Any()). + After(set1). + DoAndReturn(func(_ context.Context, req *sdcpb.GetDataRequest) (*sdcpb.GetDataResponse, error) { + if len(req.GetPath()) != 3 { + t.Fatalf("expected targeted Get for 3 mutate-on-write paths, got %d: %v", len(req.GetPath()), req.GetPath()) + } + pwJSON, _ := json.Marshal(pwHashed) + ovJSON, _ := json.Marshal(overlayCipher) + keysJSON, _ := json.Marshal(hashedKeys) + return &sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{ + { + Path: &sdcpb.Path{ + Origin: "openconfig", + IsRootBased: true, + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("dsmow:system", nil), + sdcpb.NewPathElem("hashed-password", nil), + }, + }, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_JsonIetfVal{JsonIetfVal: pwJSON}}, + }, + { + Path: &sdcpb.Path{ + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("overlay-password", nil), + }, + }, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_JsonIetfVal{JsonIetfVal: ovJSON}}, + }, + { + Path: &sdcpb.Path{ + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("hashed-key", nil), + }, + }, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_JsonIetfVal{JsonIetfVal: keysJSON}}, + }, + }, + }}, + }, nil + }).Times(1) + + intent1 := buildJSONIntent(t, f.ds, "intent1", 10, false, map[string]any{ + "system": map[string]any{ + "hashed-password": pwCleartext, + "overlay-password": overlayCleartext, + "hashed-key": []string{"raw-key-1", "raw-key-2"}, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-init", []*types.TransactionIntent{intent1}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-init): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-init"); err != nil { + t.Fatalf("TransactionConfirm(tx-init): %v", err) + } + + runningInitResp, err := f.ds.GetIntent(ctx, consts.RunningIntentName) + if err != nil { + t.Fatalf("GetIntent(running): %v", err) + } + runningInitUpds, err := runningInitResp.ToProtoUpdates(ctx) + if err != nil { + t.Fatalf("runningInitResp.ToProtoUpdates: %v", err) + } + runningInitMap := updatesByXPath(runningInitUpds) + if runningInitMap["/system/overlay-password"] != overlayCipher { + t.Fatalf("Running overlay-password = %q, want 66-char cipher %q", runningInitMap["/system/overlay-password"], overlayCipher) + } + + // Unrelated TransactionSet validates authored cleartext (not 66-char Running hash) and skips converged MOW leaves. + var unrelatedPushed []*sdcpb.Update + f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + DoAndReturn(func(setCtx context.Context, source targettypes.TargetSource) (*sdcpb.SetDataResponse, error) { + var err error + unrelatedPushed, err = source.ToProtoUpdates(setCtx, true) + return &sdcpb.SetDataResponse{}, err + }).Times(1) + + intent2 := buildJSONIntent(t, f.ds, "intent2", 20, false, map[string]any{ + "system": map[string]any{ + "hostname": "rtr-unrelated", + }, + }) + resp2, err := f.ds.TransactionSet(ctx, "tx-unrelated", []*types.TransactionIntent{intent2}, nil, time.Minute, false) + if err != nil { + t.Fatalf("TransactionSet(tx-unrelated): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-unrelated"); err != nil { + t.Fatalf("TransactionConfirm(tx-unrelated): %v", err) + } + pushedMap2 := updatesByXPath(unrelatedPushed) + if len(pushedMap2) != 1 || pushedMap2["/system/hostname"] != "rtr-unrelated" { + t.Fatalf("unrelated TransactionSet pushed %v, want only /system/hostname=rtr-unrelated", pushedMap2) + } + if respMap2 := updatesByXPath(resp2.GetUpdate()); len(respMap2) != 1 || respMap2["/system/hostname"] != "rtr-unrelated" { + t.Fatalf("unrelated TransactionSetResponse updates = %v, want only /system/hostname=rtr-unrelated", respMap2) + } + + // Re-bundled unchanged revertive intent1 alongside modified intent2 must still not re-push MOW leaves. + var rebundledPushed []*sdcpb.Update + f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + DoAndReturn(func(setCtx context.Context, source targettypes.TargetSource) (*sdcpb.SetDataResponse, error) { + var err error + rebundledPushed, err = source.ToProtoUpdates(setCtx, true) + return &sdcpb.SetDataResponse{}, err + }).Times(1) + + intent1Rebundled := buildJSONIntent(t, f.ds, "intent1", 10, false, map[string]any{ + "system": map[string]any{ + "hashed-password": pwCleartext, + "overlay-password": overlayCleartext, + "hashed-key": []string{"raw-key-1", "raw-key-2"}, + }, + }) + intent2Modified := buildJSONIntent(t, f.ds, "intent2", 20, false, map[string]any{ + "system": map[string]any{ + "hostname": "rtr-rebundled", + }, + }) + resp3, err := f.ds.TransactionSet(ctx, "tx-rebundled", []*types.TransactionIntent{intent1Rebundled, intent2Modified}, nil, time.Minute, false) + if err != nil { + t.Fatalf("TransactionSet(tx-rebundled): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-rebundled"); err != nil { + t.Fatalf("TransactionConfirm(tx-rebundled): %v", err) + } + pushedMap3 := updatesByXPath(rebundledPushed) + if len(pushedMap3) != 1 || pushedMap3["/system/hostname"] != "rtr-rebundled" { + t.Fatalf("re-bundled TransactionSet pushed %v, want only /system/hostname=rtr-rebundled", pushedMap3) + } + if respMap3 := updatesByXPath(resp3.GetUpdate()); len(respMap3) != 1 || respMap3["/system/hostname"] != "rtr-rebundled" { + t.Fatalf("re-bundled TransactionSetResponse updates = %v, want only /system/hostname=rtr-rebundled", respMap3) + } + + // Re-submitting unchanged revertive intent1 alone pushes zero updates/deletes and issues zero Get calls. + expectEmptySet(t, f.sbi) + intent1Unchanged := buildJSONIntent(t, f.ds, "intent1", 10, false, map[string]any{ + "system": map[string]any{ + "hashed-password": pwCleartext, + "overlay-password": overlayCleartext, + "hashed-key": []string{"raw-key-1", "raw-key-2"}, + }, + }) + resp4, err := f.ds.TransactionSet(ctx, "tx-idempotent", []*types.TransactionIntent{intent1Unchanged}, nil, time.Minute, false) + if err != nil { + t.Fatalf("TransactionSet(tx-idempotent): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-idempotent"); err != nil { + t.Fatalf("TransactionConfirm(tx-idempotent): %v", err) + } + if len(resp4.GetUpdate()) != 0 { + t.Fatalf("expected 0 updates on idempotent re-submission, got %v", resp4.GetUpdate()) + } + + // Zero-diff transaction when disconnected (sbi == nil) returns ErrNotConnected. + f.ds.sbi = nil + _, disconnErr := f.ds.TransactionSet(ctx, "tx-disconnected", []*types.TransactionIntent{intent1Unchanged}, nil, time.Minute, false) + if !errors.Is(disconnErr, targettypes.ErrNotConnected) { + t.Fatalf("disconnected zero-diff TransactionSet err = %v, want ErrNotConnected", disconnErr) + } + f.ds.sbi = f.sbi + + // Schema validation rejects authored cleartext violating the 32-char must constraint and the 8-char length minimum. + tooLongIntent := buildJSONIntent(t, f.ds, "intent1", 10, false, map[string]any{ + "system": map[string]any{ + "hashed-password": pwCleartext, + "overlay-password": "TooLongCleartextPasswordExceeding32Chars", + "hashed-key": []string{"raw-key-1", "raw-key-2"}, + }, + }) + invalidResp, err := f.ds.TransactionSet(ctx, "tx-invalid", []*types.TransactionIntent{tooLongIntent}, nil, time.Minute, false) + if err != nil { + t.Fatalf("TransactionSet(tx-invalid) unexpected rpc error: %v", err) + } + if errs := invalidResp.GetIntents()["intent1"].GetErrors(); len(errs) == 0 || !strings.Contains(errs[0], "overlay-password") { + t.Fatalf("expected overlay-password validation error for intent1, got %v", invalidResp) + } + + _, shortErr := f.ds.SdcpbTransactionIntentToInternalTI(ctx, &sdcpb.TransactionIntent{ + Intent: "intent1", + Priority: 10, + Update: []*sdcpb.Update{{ + Path: &sdcpb.Path{}, + Value: &sdcpb.TypedValue{ + Value: &sdcpb.TypedValue_JsonIetfVal{ + JsonIetfVal: []byte(`{"system":{"overlay-password":"short"}}`), + }, + }, + }}, + }) + if shortErr == nil { + t.Fatal("expected length constraint failure for 5-char overlay-password") + } +} + +func TestDatastore_MutateOnWrite_BaselineKeySpecificityAndOverruled(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + set1 := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + + f.sbi.EXPECT(). + Get(gomock.Any(), gomock.Any()). + After(set1). + DoAndReturn(func(_ context.Context, req *sdcpb.GetDataRequest) (*sdcpb.GetDataResponse, error) { + if len(req.GetPath()) != 1 || req.GetPath()[0].ToXPath(false) != "/system/user[username=alice]/password" { + t.Fatalf("unexpected Get paths: %v", req.GetPath()) + } + return &sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{ + { + Path: &sdcpb.Path{ + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("user", map[string]string{"username": "alice"}), + sdcpb.NewPathElem("username", nil), + }, + }, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: "alice"}}, + }, + { + Path: &sdcpb.Path{ + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("user", map[string]string{"username": "alice"}), + sdcpb.NewPathElem("password", nil), + }, + }, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: "$6$alice$hashV1"}}, + }, + }, + }}, + }, nil + }).Times(1) + + highIntent := buildJSONIntent(t, f.ds, "high-owner", 10, false, map[string]any{ + "system": map[string]any{ + "user": []any{ + map[string]any{"username": "alice", "password": "HighSecretV1"}, + }, + }, + }) + lowIntent := buildJSONIntent(t, f.ds, "low-owner", 20, false, map[string]any{ + "system": map[string]any{ + "user": []any{ + map[string]any{"username": "alice", "password": "LowSecretV1"}, + }, + }, + }) + + if _, err := f.ds.TransactionSet(ctx, "tx-1", []*types.TransactionIntent{highIntent, lowIntent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-1): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-1"); err != nil { + t.Fatalf("TransactionConfirm(tx-1): %v", err) + } + + events := collectWatchDeviationsBatch(t, f.ds) + foundOverruled := false + for _, ev := range events { + if ev.GetEvent() != sdcpb.DeviationEvent_UPDATE { + continue + } + if ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + t.Fatalf("unexpected NOT_APPLIED deviation: %v", ev) + } + if ev.GetReason() == sdcpb.DeviationReason_OVERRULED && + ev.GetPath().ToXPath(false) == "/system/user[username=alice]/password" { + foundOverruled = true + if ev.GetIntent() != "low-owner" || + ev.GetExpectedValue().GetStringVal() != "LowSecretV1" || + ev.GetCurrentValue().GetStringVal() != "HighSecretV1" { + t.Fatalf("OVERRULED event = (intent=%q, expected=%v, current=%v), want (low-owner, LowSecretV1, HighSecretV1)", + ev.GetIntent(), ev.GetExpectedValue(), ev.GetCurrentValue()) + } + } + } + if !foundOverruled { + t.Fatalf("expected OVERRULED deviation for low-owner on /system/user[username=alice]/password, got %v", events) + } + + set2 := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + f.sbi.EXPECT(). + Get(gomock.Any(), gomock.Any()). + After(set2). + Return(&sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{{ + Path: &sdcpb.Path{ + IsRootBased: true, + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("user", map[string]string{"username": "alice"}), + sdcpb.NewPathElem("password", nil), + }, + }, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: "$6$alice$hashV2"}}, + }}, + }}, + }, nil).Times(1) + + highIntentV2 := buildJSONIntent(t, f.ds, "high-owner", 10, false, map[string]any{ + "system": map[string]any{ + "user": []any{ + map[string]any{"username": "alice", "password": "HighSecretV2"}, + }, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-2", []*types.TransactionIntent{highIntentV2}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-2): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-2"); err != nil { + t.Fatalf("TransactionConfirm(tx-2): %v", err) + } + + // PreviouslyApplied super-owner changes winningOwner without pushing, proving baseline owner specificity. + superIntent, err := f.ds.SdcpbTransactionIntentToInternalTI(ctx, &sdcpb.TransactionIntent{ + Intent: "super-owner", + Priority: 5, + NonRevertive: true, + PreviouslyApplied: true, + Update: []*sdcpb.Update{{ + Path: &sdcpb.Path{}, + Value: &sdcpb.TypedValue{ + Value: &sdcpb.TypedValue_JsonIetfVal{ + JsonIetfVal: []byte(`{"system":{"user":[{"username":"alice","password":"HighSecretV2"}]}}`), + }, + }, + }}, + }) + if err != nil { + t.Fatalf("SdcpbTransactionIntentToInternalTI(super-owner): %v", err) + } + expectEmptySet(t, f.sbi) + if _, err := f.ds.TransactionSet(ctx, "tx-3", []*types.TransactionIntent{superIntent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-3): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-3"); err != nil { + t.Fatalf("TransactionConfirm(tx-3): %v", err) + } + + eventsAfterOwnerChange := collectWatchDeviationsBatch(t, f.ds) + foundNotAppliedForSuper := false + for _, ev := range eventsAfterOwnerChange { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && + ev.GetIntent() == "super-owner" && + ev.GetPath().ToXPath(false) == "/system/user[username=alice]/password" { + foundNotAppliedForSuper = true + if ev.GetExpectedValue().GetStringVal() != "HighSecretV2" { + t.Fatalf("NOT_APPLIED ExpectedValue = %v, want HighSecretV2", ev.GetExpectedValue()) + } + } + } + if !foundNotAppliedForSuper { + t.Fatalf("expected NOT_APPLIED for super-owner because baseline belonged to high-owner, got %v", eventsAfterOwnerChange) + } +} + +func TestDatastore_MutateOnWrite_ReplaceTransaction(t *testing.T) { + ctx := context.Background() + + t.Run("pure replace writes readback hash to Running", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(1) + seedIntent := buildJSONIntent(t, f.ds, "seed", 50, false, map[string]any{ + "system": map[string]any{"hostname": "before-replace"}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-seed", []*types.TransactionIntent{seedIntent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-seed): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-seed"); err != nil { + t.Fatalf("TransactionConfirm(tx-seed): %v", err) + } + orphanSeed, err := f.ds.SdcpbTransactionIntentToInternalTI(ctx, &sdcpb.TransactionIntent{ + Intent: "seed", + Priority: 50, + Delete: true, + Orphan: true, + }) + if err != nil { + t.Fatalf("orphan seed: %v", err) + } + expectEmptySet(t, f.sbi) + if _, err := f.ds.TransactionSet(ctx, "tx-orphan", []*types.TransactionIntent{orphanSeed}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-orphan): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-orphan"); err != nil { + t.Fatalf("TransactionConfirm(tx-orphan): %v", err) + } + + const ( + replaceCleartext = "ReplaceCleartext!" + replaceHashed = "$6$rounds=5000$replsalt$replhash" + overlayCleartext = "ReplaceOverlay1" + overlayCipher = "$9$rounds=10000$longsaltvalue$replace_cipher_longer_than_32_chars" + ) + + replaceSet := f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(1) + replaceGet := f.sbi.EXPECT(). + Get(gomock.Any(), gomock.Any()). + After(replaceSet). + DoAndReturn(func(_ context.Context, req *sdcpb.GetDataRequest) (*sdcpb.GetDataResponse, error) { + if req.GetDataType() != sdcpb.DataType_CONFIG { + t.Errorf("replace Get DataType = %v, want CONFIG", req.GetDataType()) + } + if len(req.GetPath()) != 2 { + t.Fatalf("replace Get paths = %v, want 2 mutate-on-write paths", req.GetPath()) + } + return &sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{ + { + Path: &sdcpb.Path{ + IsRootBased: true, + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("hashed-password", nil), + }, + }, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: replaceHashed}}, + }, + { + Path: &sdcpb.Path{ + IsRootBased: true, + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("overlay-password", nil), + }, + }, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: overlayCipher}}, + }, + }, + }}, + }, nil + }).Times(1) + expectEmptySet(t, f.sbi).After(replaceGet) + + replaceTI := buildJSONIntent(t, f.ds, consts.ReplaceIntentName, consts.ReplaceValuesPrio, false, map[string]any{ + "system": map[string]any{ + "hashed-password": replaceCleartext, + "overlay-password": overlayCleartext, + "hostname": "after-replace", + }, + }) + + if _, err := f.ds.TransactionSet(ctx, "tx-replace", nil, replaceTI, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-replace): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-replace"); err != nil { + t.Fatalf("TransactionConfirm(tx-replace): %v", err) + } + + runningResp, err := f.ds.GetIntent(ctx, consts.RunningIntentName) + if err != nil { + t.Fatalf("GetIntent(running): %v", err) + } + runningUpds, err := runningResp.ToProtoUpdates(ctx) + if err != nil { + t.Fatalf("runningResp.ToProtoUpdates: %v", err) + } + runMap := updatesByXPath(runningUpds) + if runMap["/system/hashed-password"] != replaceHashed || + runMap["/system/overlay-password"] != overlayCipher || + runMap["/system/hostname"] != "after-replace" { + t.Fatalf("Running after replace = %v, want hashed=%q overlay=%q hostname=after-replace", runMap, replaceHashed, overlayCipher) + } + }) + + t.Run("replace matching persisted intent binds baseline without second Set", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + const ( + sharedCleartext = "SharedSecret!" + hash1 = "$6$saltA$hashA" + hash2 = "$6$saltB$hashB" + ) + + initSet := f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).After(initSet).Return(&sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{{ + Path: &sdcpb.Path{ + IsRootBased: true, + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("hashed-password", nil), + }, + }, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: hash1}}, + }}, + }}, + }, nil).Times(1) + + persistedIntent := buildJSONIntent(t, f.ds, "intent1", 10, false, map[string]any{ + "system": map[string]any{ + "hashed-password": sharedCleartext, + "hostname": "same-host", + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-init", []*types.TransactionIntent{persistedIntent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-init): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-init"); err != nil { + t.Fatalf("TransactionConfirm(tx-init): %v", err) + } + + // Replace with the same cleartext binds intent1's baseline so follow-through diff is empty and issues 1 Get. + replSet := f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(1) + replGet := f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).After(replSet).Return(&sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{{ + Path: &sdcpb.Path{ + IsRootBased: true, + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("hashed-password", nil), + }, + }, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: hash2}}, + }}, + }}, + }, nil).Times(1) + expectEmptySet(t, f.sbi).After(replGet) + + replaceTI := buildJSONIntent(t, f.ds, consts.ReplaceIntentName, consts.ReplaceValuesPrio, false, map[string]any{ + "system": map[string]any{ + "hashed-password": sharedCleartext, + "hostname": "same-host", + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-replace-persisted", nil, replaceTI, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-replace-persisted): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-replace-persisted"); err != nil { + t.Fatalf("TransactionConfirm(tx-replace-persisted): %v", err) + } + }) +} + +func TestDatastore_MutateOnWrite_DryRunAndNoopSkipTargetedGet(t *testing.T) { + ctx := context.Background() + + t.Run("dryRun skips Set and targeted Get without modifying Running", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + intent := buildJSONIntent(t, f.ds, "dryrun-intent", 10, false, map[string]any{ + "system": map[string]any{ + "hashed-password": "DryRunPassword!", + "hostname": "dryrun-host", + }, + }) + resp, err := f.ds.TransactionSet(ctx, "tx-dryrun", []*types.TransactionIntent{intent}, nil, time.Minute, true) + if err != nil { + t.Fatalf("TransactionSet(dryRun): %v", err) + } + if got := updatesByXPath(resp.GetUpdate())["/system/hashed-password"]; got != "DryRunPassword!" { + t.Fatalf("dryRun response hashed-password = %q, want DryRunPassword!", got) + } + runningResp, err := f.ds.GetIntent(ctx, consts.RunningIntentName) + if err != nil { + t.Fatalf("GetIntent(running): %v", err) + } + runningUpds, err := runningResp.ToProtoUpdates(ctx) + if err != nil { + t.Fatalf("runningResp.ToProtoUpdates: %v", err) + } + if len(runningUpds) != 0 { + t.Fatalf("expected empty Running after dryRun, got %v", runningUpds) + } + }) + + t.Run("noop target skips targeted Get cleanly", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + f.ds.config.SBI = &config.SBI{Type: "noop"} + f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + + intent := buildJSONIntent(t, f.ds, "noop-intent", 10, false, map[string]any{ + "system": map[string]any{ + "hashed-password": "NoopPassword!", + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-noop-mock", []*types.TransactionIntent{intent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(noop mock): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-noop-mock"); err != nil { + t.Fatalf("TransactionConfirm(noop mock): %v", err) + } + + sc, schemaCfg := initMutateOnWriteSchema(t) + localCache, err := cache.NewLocalCache(&cacheconfig.CacheConfig{Dir: t.TempDir()}) + if err != nil { + t.Fatalf("NewLocalCache: %v", err) + } + dsCfg := &config.DatastoreConfig{ + Name: "real-noop-ds", + Schema: schemaCfg, + SBI: &config.SBI{Type: "noop"}, + Sync: &config.Sync{}, + Validation: config.NewValidationConfig(), + Deviation: &config.DeviationConfig{Interval: time.Hour}, + } + realNoopDS, err := New(ctx, dsCfg, sc, localCache) + if err != nil { + t.Fatalf("datastore.New(noop): %v", err) + } + t.Cleanup(func() { _ = realNoopDS.Stop(ctx) }) + + deadline := time.Now().Add(2 * time.Second) + for realNoopDS.ConnectionState().Status != sdcpb.TargetStatus_CONNECTED { + if time.Now().After(deadline) { + t.Fatal("timed out waiting for noop target connection") + } + time.Sleep(5 * time.Millisecond) + } + + noopTI := buildJSONIntent(t, realNoopDS, "intent1", 10, false, map[string]any{ + "system": map[string]any{ + "hashed-password": "NoopCleartextPassword", + }, + }) + if _, err := realNoopDS.TransactionSet(ctx, "tx-real-noop", []*types.TransactionIntent{noopTI}, nil, time.Minute, false); err != nil { + t.Fatalf("realNoopDS.TransactionSet: %v", err) + } + if err := realNoopDS.TransactionConfirm(ctx, "tx-real-noop"); err != nil { + t.Fatalf("realNoopDS.TransactionConfirm: %v", err) + } + }) + + t.Run("empty readback is not bound as confirmed applied value", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + setCall := f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(1) + f.sbi.EXPECT(). + Get(gomock.Any(), gomock.Any()). + After(setCall). + Return(&sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{{ + Path: &sdcpb.Path{ + IsRootBased: true, + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("hashed-password", nil), + }, + }, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: ""}}, + }}, + }}, + }, nil).Times(1) + + intent := buildJSONIntent(t, f.ds, "empty-rb-intent", 10, true, map[string]any{ + "system": map[string]any{ + "hashed-password": "SecretValue", + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-empty-rb", []*types.TransactionIntent{intent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-empty-rb): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-empty-rb"); err != nil { + t.Fatalf("TransactionConfirm(tx-empty-rb): %v", err) + } + + // Empty readback is ignored, so an empty string in Running raises NOT_APPLIED. + if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{}}, jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": ""}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning: %v", err) + } + events := collectWatchDeviationsBatch(t, f.ds) + foundNotApplied := false + for _, ev := range events { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + foundNotApplied = true + } + } + if !foundNotApplied { + t.Fatalf("expected NOT_APPLIED when readback and Running were empty string, got %v", events) + } + }) +} diff --git a/pkg/datastore/post_set_readback.go b/pkg/datastore/post_set_readback.go new file mode 100644 index 00000000..59ccdb8f --- /dev/null +++ b/pkg/datastore/post_set_readback.go @@ -0,0 +1,194 @@ +// Copyright 2024 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package datastore + +import ( + "context" + "strings" + + "github.com/sdcio/data-server/pkg/tree" + "github.com/sdcio/data-server/pkg/tree/api" + "github.com/sdcio/data-server/pkg/tree/consts" + "github.com/sdcio/data-server/pkg/tree/ops" + treetypes "github.com/sdcio/data-server/pkg/tree/types" + "github.com/sdcio/data-server/pkg/utils" + "github.com/sdcio/logger" + sdcpb "github.com/sdcio/sdc-protos/sdcpb" + "google.golang.org/protobuf/proto" +) + +func (d *Datastore) isNoopTarget() bool { + return d.config != nil && d.config.SBI != nil && strings.EqualFold(d.config.SBI.Type, "noop") +} + +func isMutateOnWriteLeafEntry(le *api.LeafEntry) bool { + return le != nil && le.GetEntry() != nil && le.GetEntry().GetSchema().IsMutateOnWrite() +} + +func collectPushedMutateOnWritePaths(updates api.LeafVariantSlice) []*sdcpb.Path { + var paths []*sdcpb.Path + seen := make(map[canonicalLeafPath]struct{}) + for _, le := range updates { + if !isMutateOnWriteLeafEntry(le) || le.GetDeleteFlag() || le.GetExplicitDeleteFlag() { + continue + } + p := le.SdcpbPath() + k := newCanonicalLeafPath(p) + if _, exists := seen[k]; !exists { + seen[k] = struct{}{} + paths = append(paths, canonicalPath(p)) + } + } + return paths +} + +// fetchMutateOnWriteReadbacks issues a single targeted CONFIG Get for paths on +// real targets and returns non-empty schema-typed leaf values keyed by canonicalLeafPath. +// Callers must hold dmutex. +func (d *Datastore) fetchMutateOnWriteReadbacks(ctx context.Context, paths []*sdcpb.Path) map[canonicalLeafPath]*sdcpb.TypedValue { + if len(paths) == 0 || d.isNoopTarget() { + return nil + } + sbi := d.getSBI() + if sbi == nil { + return nil + } + + req := &sdcpb.GetDataRequest{ + Path: paths, + DataType: sdcpb.DataType_CONFIG, + } + if d.config != nil { + req.Name = d.config.Name + if enc, ok := d.gnmiReadbackEncoding(); ok { + req.Encoding = enc + } + } + + log := logger.FromContext(ctx) + rsp, err := sbi.Get(ctx, req) + if err != nil { + log.Error(err, "post-Set targeted Get for mutate-on-write leaves failed", "severity", "WARN") + return nil + } + + converter := utils.NewConverter(d.schemaClient) + readbacks := make(map[canonicalLeafPath]*sdcpb.TypedValue, len(paths)) + for _, noti := range rsp.GetNotification() { + for _, rawUpd := range noti.GetUpdate() { + expanded, expErr := converter.ExpandUpdate(ctx, proto.Clone(rawUpd).(*sdcpb.Update)) + if expErr != nil { + log.Error(expErr, "failed expanding post-Set mutate-on-write readback", "severity", "WARN") + continue + } + for _, upd := range expanded { + if !isNonEmptyTypedValue(upd.GetValue()) { + continue + } + readbacks[newCanonicalLeafPath(upd.GetPath())] = upd.GetValue() + } + } + } + return readbacks +} + +func (d *Datastore) gnmiReadbackEncoding() (sdcpb.Encoding, bool) { + if d.config == nil || d.config.SBI == nil || d.config.SBI.GnmiOptions == nil || d.config.SBI.GnmiOptions.Encoding == "" { + return 0, false + } + enc, err := sdcpb.ParseEncoding(d.config.SBI.GnmiOptions.Encoding) + if err != nil { + return 0, false + } + return enc, true +} + +// applyReadbacksAndWriteBackRunning binds non-empty post-Set readbacks as +// confirmed applied values for pushed mutate-on-write leaves, evicts stale +// baselines when readbacks are empty or missing, and updates Running. +func (d *Datastore) applyReadbacksAndWriteBackRunning(ctx context.Context, updates api.LeafVariantSlice, deletes treetypes.DeleteEntriesList, readbacks map[canonicalLeafPath]*sdcpb.TypedValue) error { + return d.writeReadbacksToRunning(ctx, updates, deletes, readbacks, func(le *api.LeafEntry, rb *sdcpb.TypedValue, ok bool) { + if ok { + d.confirmedApplied.Record(le.SdcpbPath(), le.Owner(), le.Value(), rb) + } else { + d.confirmedApplied.Delete(le.SdcpbPath()) + } + }) +} + +// reconcileReplaceReadbacksAndWriteBackRunning clears prior baselines after a +// full-config replace, binds non-empty readbacks to matching winning persisted +// owners when present, and writes confirmed applied values into Running. +func (d *Datastore) reconcileReplaceReadbacksAndWriteBackRunning(ctx context.Context, updates api.LeafVariantSlice, deletes treetypes.DeleteEntriesList, readbacks map[canonicalLeafPath]*sdcpb.TypedValue) error { + d.confirmedApplied.ClearAll() + + var persistedIntents *tree.RootEntry + if len(readbacks) > 0 { + if root, err := d.NewEmptyTree(ctx); err == nil { + if _, loadErr := d.LoadAllButRunningIntents(ctx, root); loadErr == nil && root.FinishInsertionPhase(ctx) == nil { + persistedIntents = root + } + } + } + + return d.writeReadbacksToRunning(ctx, updates, deletes, readbacks, func(le *api.LeafEntry, rb *sdcpb.TypedValue, ok bool) { + if !ok { + return + } + if owner, matched := winningPersistedOwnerWithValue(ctx, persistedIntents, le.SdcpbPath(), le.Value()); matched { + d.confirmedApplied.Record(le.SdcpbPath(), owner, le.Value(), rb) + } + }) +} + +func (d *Datastore) writeReadbacksToRunning( + ctx context.Context, + updates api.LeafVariantSlice, + deletes treetypes.DeleteEntriesList, + readbacks map[canonicalLeafPath]*sdcpb.TypedValue, + onMutateOnWrite func(le *api.LeafEntry, rb *sdcpb.TypedValue, hasReadback bool), +) error { + runningUpdates := make([]*treetypes.PathAndUpdate, 0, len(updates)) + for _, le := range updates { + runVal := le.Value() + if isMutateOnWriteLeafEntry(le) { + rb, ok := readbacks[newCanonicalLeafPath(le.SdcpbPath())] + onMutateOnWrite(le, rb, ok) + if ok { + runVal = proto.Clone(rb).(*sdcpb.TypedValue) + } + } + runningUpdates = append(runningUpdates, treetypes.NewPathAndUpdate( + le.SdcpbPath(), + treetypes.NewUpdate(nil, runVal, consts.RunningValuesPrio, consts.RunningIntentName, le.Timestamp()), + )) + } + return d.writeBackRunningUpdates(ctx, runningUpdates, deletes) +} + +func winningPersistedOwnerWithValue(ctx context.Context, persistedIntents *tree.RootEntry, path *sdcpb.Path, val *sdcpb.TypedValue) (string, bool) { + if persistedIntents == nil { + return "", false + } + entry, err := ops.NavigateSdcpbPath(ctx, persistedIntents.Entry, path) + if err != nil || entry == nil { + return "", false + } + highest := entry.GetLeafVariants().GetHighestPrecedence(false, false, false) + if highest == nil || !api.TypedValuesEqual(highest.Value(), val) { + return "", false + } + return highest.Owner(), true +} diff --git a/pkg/datastore/sync.go b/pkg/datastore/sync.go index 5ccd0e87..08c19b12 100644 --- a/pkg/datastore/sync.go +++ b/pkg/datastore/sync.go @@ -121,7 +121,7 @@ func (d *Datastore) ApplyToRunning(ctx context.Context, deletes []*sdcpb.Path, i } func (d *Datastore) NewEmptyTree(ctx context.Context) (*tree.RootEntry, error) { - tc := tree.NewTreeContext(d.schemaClient, d.taskPool) + tc := d.newTreeContext() newTree, err := tree.NewTreeRoot(ctx, tc) if err != nil { return nil, err diff --git a/pkg/datastore/transaction_rpc.go b/pkg/datastore/transaction_rpc.go index 1b3a61f4..1b7c6152 100644 --- a/pkg/datastore/transaction_rpc.go +++ b/pkg/datastore/transaction_rpc.go @@ -84,7 +84,7 @@ func (d *Datastore) replaceIntent(ctx context.Context, transaction *types.Transa ctx = logger.IntoContext(ctx, log) // create a new TreeContext - tc := tree.NewTreeContext(d.schemaClient, d.taskPool) + tc := d.newTreeContext() // create a new TreeRoot to collect validate and hand to SBI.Set() root, err := tree.NewTreeRoot(ctx, tc) @@ -152,9 +152,9 @@ func (d *Datastore) replaceIntent(ctx context.Context, transaction *types.Transa // retrieve the data that is meant to be send southbound (towards the device) updates := root.GetHighestPrecedence(true) deletes := treetypes.DeleteEntriesList{root} + readbacks := d.fetchMutateOnWriteReadbacks(ctx, collectPushedMutateOnWritePaths(updates)) - // OPTIMISTIC WRITEBACK TO RUNNING / syncTree - err = d.writeBackSyncTree(ctx, updates, deletes) + err = d.reconcileReplaceReadbacksAndWriteBackRunning(ctx, updates, deletes, readbacks) if err != nil { return nil, err } @@ -194,7 +194,6 @@ func (d *Datastore) LoadAllButRunningIntents(ctx context.Context, root *tree.Roo // lowlevelTransactionSet func (d *Datastore) lowlevelTransactionSet(ctx context.Context, transaction *types.Transaction, dryRun bool) (*sdcpb.TransactionSetResponse, error) { log := logger.FromContext(ctx) - // create a new TreeRoot d.syncTreeMutex.RLock() root, err := d.syncTree.DeepCopy(ctx) d.syncTreeMutex.RUnlock() @@ -332,12 +331,12 @@ func (d *Datastore) lowlevelTransactionSet(ctx context.Context, transaction *typ return result, nil } - // apply the resulting config to the device dataResp, err := d.applyIntent(ctx, adapter.NewEntryOutputAdapter(root.Entry)) if err != nil { return nil, err } result.Warnings = append(result.Warnings, dataResp.GetWarnings()...) + readbacks := d.fetchMutateOnWriteReadbacks(ctx, collectPushedMutateOnWritePaths(updates)) log.Info("transaction applied") @@ -381,8 +380,7 @@ func (d *Datastore) lowlevelTransactionSet(ctx context.Context, transaction *typ } } - // OPTIMISTIC WRITEBACK TO RUNNING / syncTree - err = d.writeBackSyncTree(ctx, updates, deletes) + err = d.applyReadbacksAndWriteBackRunning(ctx, updates, deletes, readbacks) if err != nil { return nil, err } @@ -392,10 +390,9 @@ func (d *Datastore) lowlevelTransactionSet(ctx context.Context, transaction *typ return result, nil } -// writeBackSyncTree applies the provided changes to the syncTree and applies to the running cache intent -func (d *Datastore) writeBackSyncTree(ctx context.Context, updates api.LeafVariantSlice, deletes treetypes.DeleteEntriesList) error { +// writeBackRunningUpdates applies running updates and deletes to syncTree and persists Running. +func (d *Datastore) writeBackRunningUpdates(ctx context.Context, runningUpdates []*treetypes.PathAndUpdate, deletes treetypes.DeleteEntriesList) error { log := logger.FromContext(ctx) - runningUpdates := updates.ToUpdateSlice().CopyWithNewOwnerAndPrio(consts.RunningIntentName, consts.RunningValuesPrio) // wrap the lock in an anonymous function to be able to utilize defer for the unlock err := func() error { diff --git a/pkg/tree/api/leaf_variants.go b/pkg/tree/api/leaf_variants.go index c3a9f525..a9db5acd 100644 --- a/pkg/tree/api/leaf_variants.go +++ b/pkg/tree/api/leaf_variants.go @@ -376,6 +376,32 @@ func (lv *LeafVariants) GetHighestPrecedence(onlyNewOrUpdated bool, includeDefau return nil } +// DriftBaseline returns the confirmed applied value for highest when registered +// for this leaf's path, owner, and intended value, falling back to highest.Value(). +func (lv *LeafVariants) DriftBaseline(highest *LeafEntry) *sdcpb.TypedValue { + if highest == nil { + return nil + } + if lv == nil || lv.tc == nil || lv.parentEntry == nil { + return highest.Value() + } + if highest.Owner() == treeconsts.RunningIntentName || highest.Owner() == treeconsts.DefaultsIntentName { + return highest.Value() + } + if confirmed := lv.tc.ConfirmedAppliedValue(lv.parentEntry.SdcpbPath(), highest.Owner(), highest.Value()); confirmed != nil { + return confirmed + } + return highest.Value() +} + +// TypedValuesEqual compares two TypedValues by value, handling unset Value oneofs safely. +func TypedValuesEqual(a, b *sdcpb.TypedValue) bool { + if a.GetValue() == nil || b.GetValue() == nil { + return a.GetValue() == nil && b.GetValue() == nil + } + return a.Equal(b) +} + // highestIsUnequalRunning checks if the highest precedence LeafEntry is unequal to the running LeafEntry // Expects the caller to hold the read lock on lesMutex. func (lv *LeafVariants) highestIsUnequalRunning(highest *LeafEntry) bool { @@ -394,10 +420,7 @@ func (lv *LeafVariants) highestIsUnequalRunning(highest *LeafEntry) bool { return true } - // ignore errors, they should not happen :-P I know... should... - rval := runVal.Value() - hval := highest.Value() - return !rval.Equal(hval) + return !TypedValuesEqual(runVal.Value(), lv.DriftBaseline(highest)) } // GetByOwner returns the entry that is owned by the given owner, @@ -524,8 +547,7 @@ func (lv *LeafVariants) GetDeviations(ctx context.Context, ch chan<- *types.Devi return } - // if highest exists but not running OR running != highest - if (running == nil && highest != nil) || !running.Value().Equal(highest.Value()) { + if running == nil || !TypedValuesEqual(running.Value(), lv.DriftBaseline(highest)) { de := types.NewDeviationEntry(highest.Owner(), types.DeviationReasonNotApplied, sdcpbPath).SetExpectedValue(highest.Value()) if running != nil { de.SetCurrentValue(running.Value()) diff --git a/pkg/tree/api/tree_context.go b/pkg/tree/api/tree_context.go index d14b59fc..5fc43391 100644 --- a/pkg/tree/api/tree_context.go +++ b/pkg/tree/api/tree_context.go @@ -3,12 +3,22 @@ package api import ( schemaClient "github.com/sdcio/data-server/pkg/datastore/clients/schema" "github.com/sdcio/data-server/pkg/pool" + sdcpb "github.com/sdcio/sdc-protos/sdcpb" ) +// ConfirmedAppliedValueResolver resolves the confirmed applied value observed +// on the target for a mutate-on-write leaf's canonical path, winning owner, and +// current intended value. Lookup returns nil when no baseline matches. +type ConfirmedAppliedValueResolver interface { + Lookup(path *sdcpb.Path, owner string, intendedValue *sdcpb.TypedValue) *sdcpb.TypedValue +} + type TreeContext interface { PoolFactory() pool.VirtualPoolFactory SchemaClient() schemaClient.SchemaClientBound DeepCopy() TreeContext ExplicitDeletes() *DeletePathSet NonRevertiveInfo() NonRevertiveInfos + // ConfirmedAppliedValue returns the confirmed applied value matching path, owner, and intendedValue, or nil when none matches. + ConfirmedAppliedValue(path *sdcpb.Path, owner string, intendedValue *sdcpb.TypedValue) *sdcpb.TypedValue } diff --git a/pkg/tree/confirmed_applied_value_test.go b/pkg/tree/confirmed_applied_value_test.go new file mode 100644 index 00000000..04ed53a5 --- /dev/null +++ b/pkg/tree/confirmed_applied_value_test.go @@ -0,0 +1,276 @@ +// Copyright 2024 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package tree_test + +import ( + "context" + "runtime" + "testing" + + schemaClient "github.com/sdcio/data-server/pkg/datastore/clients/schema" + "github.com/sdcio/data-server/pkg/pool" + "github.com/sdcio/data-server/pkg/tree" + "github.com/sdcio/data-server/pkg/tree/api" + "github.com/sdcio/data-server/pkg/tree/consts" + "github.com/sdcio/data-server/pkg/tree/ops" + "github.com/sdcio/data-server/pkg/tree/processors" + "github.com/sdcio/data-server/pkg/tree/types" + "github.com/sdcio/data-server/pkg/utils/testhelper" + sdcpb "github.com/sdcio/sdc-protos/sdcpb" +) + +type stubBaselineResolver struct { + path string + owner string + intended *sdcpb.TypedValue + confirmed *sdcpb.TypedValue +} + +func (s *stubBaselineResolver) Lookup(path *sdcpb.Path, owner string, intendedValue *sdcpb.TypedValue) *sdcpb.TypedValue { + if s == nil || path == nil || intendedValue == nil { + return nil + } + if path.ToXPath(false) == s.path && owner == s.owner && intendedValue.Equal(s.intended) { + return s.confirmed + } + return nil +} + +func stringTV(v string) *sdcpb.TypedValue { + return &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: v}} +} + +func TestTree_ConfirmedAppliedValueBaseline(t *testing.T) { + ctx := context.Background() + sc, schemaCfg, err := testhelper.InitSDCIOSchema() + if err != nil { + t.Fatalf("InitSDCIOSchema: %v", err) + } + scb := schemaClient.NewSchemaClientBound(schemaCfg, sc) + vpf := pool.NewSharedTaskPool(ctx, runtime.GOMAXPROCS(0)) + + leafPath := &sdcpb.Path{ + IsRootBased: true, + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("interface", map[string]string{"name": "ethernet-1/1"}), + sdcpb.NewPathElem("description", nil), + }, + } + keyPath := &sdcpb.Path{ + IsRootBased: true, + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("interface", map[string]string{"name": "ethernet-1/1"}), + sdcpb.NewPathElem("name", nil), + }, + } + + authored := stringTV("cleartext-secret") + confirmed := stringTV("$6$rounds=5000$salt$hashed") + diverged := stringTV("$6$rounds=5000$other$tampered") + + t.Run("nil-safe TreeContext without resolver falls back to literal intended value", func(t *testing.T) { + var nilTC *tree.TreeContext + if got := nilTC.ConfirmedAppliedValue(leafPath, "intent1", authored); got != nil { + t.Fatalf("nil TreeContext returned %v, want nil", got) + } + zeroTC := &tree.TreeContext{} + if got := zeroTC.ConfirmedAppliedValue(leafPath, "intent1", authored); got != nil { + t.Fatalf("zero TreeContext returned %v, want nil", got) + } + + tc := tree.NewTreeContext(scb, vpf) + root, err := tree.NewTreeRoot(ctx, tc) + if err != nil { + t.Fatalf("NewTreeRoot: %v", err) + } + err = root.AddUpdatesRecursive(ctx, []*types.PathAndUpdate{ + types.NewPathAndUpdate(keyPath, types.NewUpdate(nil, stringTV("ethernet-1/1"), 10, "intent1", 0)), + types.NewPathAndUpdate(leafPath, types.NewUpdate(nil, authored, 10, "intent1", 0)), + types.NewPathAndUpdate(keyPath, types.NewUpdate(nil, stringTV("ethernet-1/1"), consts.RunningValuesPrio, consts.RunningIntentName, 0)), + types.NewPathAndUpdate(leafPath, types.NewUpdate(nil, confirmed, consts.RunningValuesPrio, consts.RunningIntentName, 0)), + }, types.NewUpdateInsertFlags()) + if err != nil { + t.Fatalf("AddUpdatesRecursive: %v", err) + } + if err := root.FinishInsertionPhase(ctx); err != nil { + t.Fatalf("FinishInsertionPhase: %v", err) + } + + upds := root.GetHighestPrecedence(true) + if len(upds) != 1 || !upds[0].Value().Equal(authored) { + t.Fatalf("expected 1 update with authored value when no baseline resolver is set, got %v", upds) + } + }) + + t.Run("converged baseline suppresses diff, NOT_APPLIED deviation, and BlameConfig deviation while preserving authored values", func(t *testing.T) { + var resolver api.ConfirmedAppliedValueResolver = &stubBaselineResolver{ + path: "/interface[name=ethernet-1/1]/description", + owner: "intent1", + intended: authored, + confirmed: confirmed, + } + tc := tree.NewTreeContext(scb, vpf, tree.WithConfirmedAppliedValues(resolver)) + origRoot, err := tree.NewTreeRoot(ctx, tc) + if err != nil { + t.Fatalf("NewTreeRoot: %v", err) + } + // DeepCopy must preserve the wired baseline resolver. + root, err := origRoot.DeepCopy(ctx) + if err != nil { + t.Fatalf("DeepCopy: %v", err) + } + + overruledVal := stringTV("secondary-cleartext") + err = root.AddUpdatesRecursive(ctx, []*types.PathAndUpdate{ + types.NewPathAndUpdate(keyPath, types.NewUpdate(nil, stringTV("ethernet-1/1"), 10, "intent1", 0)), + types.NewPathAndUpdate(leafPath, types.NewUpdate(nil, authored, 10, "intent1", 0)), + types.NewPathAndUpdate(keyPath, types.NewUpdate(nil, stringTV("ethernet-1/1"), 20, "intent2", 0)), + types.NewPathAndUpdate(leafPath, types.NewUpdate(nil, overruledVal, 20, "intent2", 0)), + types.NewPathAndUpdate(keyPath, types.NewUpdate(nil, stringTV("ethernet-1/1"), consts.RunningValuesPrio, consts.RunningIntentName, 0)), + types.NewPathAndUpdate(leafPath, types.NewUpdate(nil, confirmed, consts.RunningValuesPrio, consts.RunningIntentName, 0)), + }, types.NewUpdateInsertFlags()) + if err != nil { + t.Fatalf("AddUpdatesRecursive: %v", err) + } + if err := root.FinishInsertionPhase(ctx); err != nil { + t.Fatalf("FinishInsertionPhase: %v", err) + } + + // 1. Diffing: Running == confirmed -> zero new/updated entries. + if upds := root.GetHighestPrecedence(true); len(upds) != 0 { + t.Fatalf("expected 0 updates when Running matches confirmed baseline, got %v", upds) + } + + // 2. Deviations: zero NOT_APPLIED; OVERRULED still reports authored values. + devCh := make(chan *types.DeviationEntry, 16) + if err := ops.GetDeviations(ctx, root.Entry, &ops.GetDeviationParams{Ch: devCh}, vpf); err != nil { + t.Fatalf("GetDeviations: %v", err) + } + close(devCh) + + var devs []*types.DeviationEntry + for d := range devCh { + devs = append(devs, d) + } + if len(devs) != 1 { + t.Fatalf("expected exactly 1 OVERRULED deviation and 0 NOT_APPLIED, got %d: %+v", len(devs), devs) + } + if devs[0].Reason() != types.DeviationReasonOverruled || devs[0].IntentName() != "intent2" { + t.Fatalf("unexpected deviation: reason=%v intent=%s", devs[0].Reason(), devs[0].IntentName()) + } + if !devs[0].ExpectedValue().Equal(overruledVal) || !devs[0].CurrentValue().Equal(authored) { + t.Fatalf("OVERRULED values = (expected=%v, current=%v), want (%v, %v)", + devs[0].ExpectedValue(), devs[0].CurrentValue(), overruledVal, authored) + } + + // 3. BlameConfig: Value is winning owner's authored value, DeviationValue is nil. + bp := processors.NewBlameConfigProcessor(&processors.BlameConfigProcessorParams{}) + blame, err := bp.Run(ctx, root.Entry, vpf) + if err != nil { + t.Fatalf("BlameConfig: %v", err) + } + descBlame := testhelper.FindBlameElement(blame, "interface", "ethernet-1/1", "description") + if descBlame == nil { + t.Fatalf("missing description blame node in %v", blame) + } + if descBlame.GetOwner() != "intent1" || !descBlame.GetValue().Equal(authored) { + t.Fatalf("BlameConfig owner/value = (%q, %v), want (%q, %v)", + descBlame.GetOwner(), descBlame.GetValue(), "intent1", authored) + } + if descBlame.GetDeviationValue() != nil { + t.Fatalf("expected nil DeviationValue when Running matches confirmed baseline, got %v", descBlame.GetDeviationValue()) + } + }) + + t.Run("diverged Running and nil Running still trigger diff, NOT_APPLIED with authored ExpectedValue, and BlameConfig deviation", func(t *testing.T) { + resolver := &stubBaselineResolver{ + path: "/interface[name=ethernet-1/1]/description", + owner: "intent1", + intended: authored, + confirmed: confirmed, + } + + for _, tcCase := range []struct { + name string + runningVal *sdcpb.TypedValue + }{ + {name: "Running differs from confirmed baseline", runningVal: diverged}, + {name: "Running is nil despite confirmed baseline", runningVal: nil}, + } { + t.Run(tcCase.name, func(t *testing.T) { + tc := tree.NewTreeContext(scb, vpf, tree.WithConfirmedAppliedValues(resolver)) + root, err := tree.NewTreeRoot(ctx, tc) + if err != nil { + t.Fatalf("NewTreeRoot: %v", err) + } + paus := []*types.PathAndUpdate{ + types.NewPathAndUpdate(keyPath, types.NewUpdate(nil, stringTV("ethernet-1/1"), 10, "intent1", 0)), + types.NewPathAndUpdate(leafPath, types.NewUpdate(nil, authored, 10, "intent1", 0)), + types.NewPathAndUpdate(keyPath, types.NewUpdate(nil, stringTV("ethernet-1/1"), consts.RunningValuesPrio, consts.RunningIntentName, 0)), + } + if tcCase.runningVal != nil { + paus = append(paus, types.NewPathAndUpdate(leafPath, types.NewUpdate(nil, tcCase.runningVal, consts.RunningValuesPrio, consts.RunningIntentName, 0))) + } + if err := root.AddUpdatesRecursive(ctx, paus, types.NewUpdateInsertFlags()); err != nil { + t.Fatalf("AddUpdatesRecursive: %v", err) + } + if err := root.FinishInsertionPhase(ctx); err != nil { + t.Fatalf("FinishInsertionPhase: %v", err) + } + + upds := root.GetHighestPrecedence(true) + if len(upds) != 1 || !upds[0].Value().Equal(authored) { + t.Fatalf("expected 1 update with authored value, got %v", upds) + } + + devCh := make(chan *types.DeviationEntry, 8) + if err := ops.GetDeviations(ctx, root.Entry, &ops.GetDeviationParams{Ch: devCh}, vpf); err != nil { + t.Fatalf("GetDeviations: %v", err) + } + close(devCh) + + var devs []*types.DeviationEntry + for d := range devCh { + devs = append(devs, d) + } + if len(devs) != 1 || devs[0].Reason() != types.DeviationReasonNotApplied { + t.Fatalf("expected 1 NOT_APPLIED deviation, got %+v", devs) + } + if !devs[0].ExpectedValue().Equal(authored) { + t.Fatalf("NOT_APPLIED ExpectedValue = %v, want authored %v", devs[0].ExpectedValue(), authored) + } + if tcCase.runningVal == nil && devs[0].CurrentValue() != nil { + t.Fatalf("expected nil CurrentValue when Running is nil, got %v", devs[0].CurrentValue()) + } + if tcCase.runningVal != nil && !devs[0].CurrentValue().Equal(tcCase.runningVal) { + t.Fatalf("NOT_APPLIED CurrentValue = %v, want %v", devs[0].CurrentValue(), tcCase.runningVal) + } + + bp := processors.NewBlameConfigProcessor(&processors.BlameConfigProcessorParams{}) + blame, err := bp.Run(ctx, root.Entry, vpf) + if err != nil { + t.Fatalf("BlameConfig: %v", err) + } + descBlame := testhelper.FindBlameElement(blame, "interface", "ethernet-1/1", "description") + if descBlame == nil || !descBlame.GetValue().Equal(authored) { + t.Fatalf("BlameConfig Value = %v, want authored %v", descBlame, authored) + } + if descBlame.GetDeviationValue() == nil { + t.Fatalf("expected non-nil DeviationValue on %s", tcCase.name) + } + }) + } + }) +} diff --git a/pkg/tree/ops/validation/validation_dispatch.go b/pkg/tree/ops/validation/validation_dispatch.go index f972e3ba..b83d0967 100644 --- a/pkg/tree/ops/validation/validation_dispatch.go +++ b/pkg/tree/ops/validation/validation_dispatch.go @@ -5,9 +5,18 @@ import ( "github.com/sdcio/data-server/pkg/config" "github.com/sdcio/data-server/pkg/tree/api" + "github.com/sdcio/data-server/pkg/tree/consts" "github.com/sdcio/data-server/pkg/tree/types" ) +func validatedLeafVariant(e api.Entry) *api.LeafEntry { + lv := e.GetLeafVariants().GetHighestPrecedence(false, true, false) + if lv != nil && lv.Owner() == consts.RunningIntentName && e.GetSchema().IsMutateOnWrite() { + return nil + } + return lv +} + // ValidationFunc is the common signature for all validation checks. type ValidationFunc func(ctx context.Context, e api.Entry, resultChan chan<- *types.ValidationResultEntry, stats *types.ValidationStats) diff --git a/pkg/tree/ops/validation/validation_entry_length.go b/pkg/tree/ops/validation/validation_entry_length.go index fee95d1d..3c61b756 100644 --- a/pkg/tree/ops/validation/validation_entry_length.go +++ b/pkg/tree/ops/validation/validation_entry_length.go @@ -17,7 +17,7 @@ func validateLength(_ context.Context, e api.Entry, resultChan chan<- *types.Val return } - lv := e.GetLeafVariants().GetHighestPrecedence(false, true, false) + lv := validatedLeafVariant(e) if lv == nil { return } diff --git a/pkg/tree/ops/validation/validation_entry_must.go b/pkg/tree/ops/validation/validation_entry_must.go index 853e472e..b219235b 100644 --- a/pkg/tree/ops/validation/validation_entry_must.go +++ b/pkg/tree/ops/validation/validation_entry_must.go @@ -26,8 +26,14 @@ func validateMustStatements(ctx context.Context, e api.Entry, resultChan chan<- case *sdcpb.SchemaElem_Container: mustStatements = schem.Container.GetMustStatements() case *sdcpb.SchemaElem_Leaflist: + if validatedLeafVariant(e) == nil { + return + } mustStatements = schem.Leaflist.GetMustStatements() case *sdcpb.SchemaElem_Field: + if validatedLeafVariant(e) == nil { + return + } mustStatements = schem.Field.GetMustStatements() } diff --git a/pkg/tree/ops/validation/validation_entry_pattern.go b/pkg/tree/ops/validation/validation_entry_pattern.go index edcfa236..52f06bd1 100644 --- a/pkg/tree/ops/validation/validation_entry_pattern.go +++ b/pkg/tree/ops/validation/validation_entry_pattern.go @@ -41,7 +41,7 @@ func validatePattern(_ context.Context, e api.Entry, resultChan chan<- *types.Va return } - lv := e.GetLeafVariants().GetHighestPrecedence(false, true, false) + lv := validatedLeafVariant(e) if lv == nil { return } diff --git a/pkg/tree/ops/validation/validation_entry_range.go b/pkg/tree/ops/validation/validation_entry_range.go index 6dd50f43..46676fed 100644 --- a/pkg/tree/ops/validation/validation_entry_range.go +++ b/pkg/tree/ops/validation/validation_entry_range.go @@ -19,7 +19,7 @@ func validateRange(_ context.Context, e api.Entry, resultChan chan<- *types.Vali return } - lv := e.GetLeafVariants().GetHighestPrecedence(false, true, false) + lv := validatedLeafVariant(e) if lv == nil { return } diff --git a/pkg/tree/processors/processor_blame_config.go b/pkg/tree/processors/processor_blame_config.go index cc970fdd..f99e2b0e 100644 --- a/pkg/tree/processors/processor_blame_config.go +++ b/pkg/tree/processors/processor_blame_config.go @@ -10,7 +10,6 @@ import ( "github.com/sdcio/data-server/pkg/tree/ops" "github.com/sdcio/data-server/pkg/tree/types" sdcpb "github.com/sdcio/sdc-protos/sdcpb" - "google.golang.org/protobuf/proto" ) type BlameConfigProcessor struct { @@ -85,25 +84,20 @@ func (t *BlameConfigTask) Run(ctx context.Context, submit func(pool.Task) error) } } - // process Value - highestLe := t.selfEntry.GetLeafVariants().GetHighestPrecedence(false, true, true) + lvs := t.selfEntry.GetLeafVariants() + highestLe := lvs.GetHighestPrecedence(false, true, true) if highestLe != nil { if highestLe.Owner() != consts.DefaultsIntentName || t.context.IncludeDefaults { t.self.SetValue(highestLe.Value()).SetOwner(highestLe.Owner()) - // check if running equals the expected - runningLe := t.selfEntry.GetLeafVariants().GetRunning() + runningLe := lvs.GetRunning() switch { case runningLe != nil: - // if running value is different from the highest precedence value, then we have a deviation, - // so we set the deviation value to the running value - if !proto.Equal(runningLe.Value(), highestLe.Value()) { + if !api.TypedValuesEqual(runningLe.Value(), lvs.DriftBaseline(highestLe)) { t.self.SetDeviationValue(runningLe.Value()) } case runningLe == nil && highestLe.Owner() != consts.DefaultsIntentName: - // if running is nil and highest is not from default, then the deviation is from a non-existing running value, - // so we set it to empty t.self.SetDeviationValue(&sdcpb.TypedValue{}) } } diff --git a/pkg/tree/tree_context.go b/pkg/tree/tree_context.go index d9c821b3..3deaac80 100644 --- a/pkg/tree/tree_context.go +++ b/pkg/tree/tree_context.go @@ -4,29 +4,48 @@ import ( schemaClient "github.com/sdcio/data-server/pkg/datastore/clients/schema" "github.com/sdcio/data-server/pkg/pool" "github.com/sdcio/data-server/pkg/tree/api" + sdcpb "github.com/sdcio/sdc-protos/sdcpb" ) +// TreeContextOption configures optional collaborators on a TreeContext. +type TreeContextOption func(*TreeContext) + +// WithConfirmedAppliedValues wires a read-only baseline resolver for mutate-on-write leaves. +func WithConfirmedAppliedValues(resolver api.ConfirmedAppliedValueResolver) TreeContextOption { + return func(tc *TreeContext) { + tc.confirmedAppliedValues = resolver + } +} + type TreeContext struct { - schemaClient schemaClient.SchemaClientBound - nonRevertiveInfo api.NonRevertiveInfos - explicitDeletes *api.DeletePathSet - poolFactory pool.VirtualPoolFactory + schemaClient schemaClient.SchemaClientBound + nonRevertiveInfo api.NonRevertiveInfos + explicitDeletes *api.DeletePathSet + poolFactory pool.VirtualPoolFactory + confirmedAppliedValues api.ConfirmedAppliedValueResolver } -func NewTreeContext(sc schemaClient.SchemaClientBound, poolFactory pool.VirtualPoolFactory) *TreeContext { - return &TreeContext{ +func NewTreeContext(sc schemaClient.SchemaClientBound, poolFactory pool.VirtualPoolFactory, opts ...TreeContextOption) *TreeContext { + tc := &TreeContext{ schemaClient: sc, nonRevertiveInfo: api.NewNonRevertiveInfos(), explicitDeletes: api.NewDeletePaths(), poolFactory: poolFactory, } + for _, opt := range opts { + if opt != nil { + opt(tc) + } + } + return tc } // deepCopy root is required to be set manually func (t *TreeContext) DeepCopy() api.TreeContext { tc := &TreeContext{ - schemaClient: t.schemaClient, - poolFactory: t.poolFactory, + schemaClient: t.schemaClient, + poolFactory: t.poolFactory, + confirmedAppliedValues: t.confirmedAppliedValues, } tc.nonRevertiveInfo = t.nonRevertiveInfo.DeepCopy() @@ -49,3 +68,10 @@ func (t *TreeContext) ExplicitDeletes() *api.DeletePathSet { func (t *TreeContext) NonRevertiveInfo() api.NonRevertiveInfos { return t.nonRevertiveInfo } + +func (t *TreeContext) ConfirmedAppliedValue(path *sdcpb.Path, owner string, intendedValue *sdcpb.TypedValue) *sdcpb.TypedValue { + if t == nil || t.confirmedAppliedValues == nil { + return nil + } + return t.confirmedAppliedValues.Lookup(path, owner, intendedValue) +} diff --git a/pkg/utils/converter.go b/pkg/utils/converter.go index a87e6b44..b3537659 100644 --- a/pkg/utils/converter.go +++ b/pkg/utils/converter.go @@ -96,25 +96,13 @@ func (c *Converter) ExpandUpdate(ctx context.Context, upd *sdcpb.Update) ([]*sdc } return nil, nil } - var v any - var err error - var jsonDecoder *json.Decoder - switch upd.GetValue().Value.(type) { - case *sdcpb.TypedValue_JsonIetfVal: - jsonDecoder = json.NewDecoder(bytes.NewReader(upd.GetValue().GetJsonIetfVal())) - case *sdcpb.TypedValue_JsonVal: - jsonDecoder = json.NewDecoder(bytes.NewReader(upd.GetValue().GetJsonVal())) - default: - return []*sdcpb.Update{upd}, nil - } - // don't decode into float64 but keep as a string - // this solves issues created by reading long integers - jsonDecoder.UseNumber() - err = jsonDecoder.Decode(&v) + v, hasJSON, err := decodeTypedValueJSON(upd.GetValue()) if err != nil { return nil, err } - // log.Debugf("update has jsonVal: %T, %v\n", v, v) + if !hasJSON { + return []*sdcpb.Update{upd}, nil + } rs, err := c.ExpandContainerValue(ctx, upd.GetPath(), v, rsp) if err != nil { return nil, err @@ -123,30 +111,15 @@ func (c *Converter) ExpandUpdate(ctx context.Context, upd *sdcpb.Update) ([]*sdc return upds, nil case *sdcpb.SchemaElem_Field: - var v interface{} - var err error - - var jsonValue []byte if upd.GetValue() == nil { log.Error(nil, "value is nil", "path", upd.Path.ToXPath(false)) return nil, nil } - switch upd.GetValue().Value.(type) { - case *sdcpb.TypedValue_JsonVal: - jsonValue = upd.GetValue().GetJsonVal() - case *sdcpb.TypedValue_JsonIetfVal: - jsonValue = upd.GetValue().GetJsonIetfVal() + v, hasJSON, err := decodeTypedValueJSON(upd.GetValue()) + if err != nil { + return nil, err } - - // process value - if jsonValue != nil { - decoder := json.NewDecoder(bytes.NewReader(jsonValue)) - // Keep numbers as json.Number to avoid precision loss for large integers. - decoder.UseNumber() - err = decoder.Decode(&v) - if err != nil { - return nil, err - } + if hasJSON { upd.Value, err = sdcpb.ConvertJsonValueToTv(v, rsp.Field.GetType()) if err != nil { return nil, err @@ -169,12 +142,54 @@ func (c *Converter) ExpandUpdate(ctx context.Context, upd *sdcpb.Update) ([]*sdc upds = append(upds, upd) return upds, nil case *sdcpb.SchemaElem_Leaflist: + decoded, hasJSON, err := decodeTypedValueJSON(upd.GetValue()) + if err != nil { + return nil, err + } + if hasJSON { + arr, ok := decoded.([]any) + if !ok { + return nil, fmt.Errorf("leaflist %s expects JSON array, got %T", upd.GetPath().ToXPath(false), decoded) + } + elems := make([]*sdcpb.TypedValue, 0, len(arr)) + for _, item := range arr { + elemTV, err := sdcpb.ConvertJsonValueToTv(item, rsp.Leaflist.GetType()) + if err != nil { + return nil, err + } + elems = append(elems, elemTV) + } + upd.Value = &sdcpb.TypedValue{ + Value: &sdcpb.TypedValue_LeaflistVal{ + LeaflistVal: &sdcpb.ScalarArray{Element: elems}, + }, + } + } upds = append(upds, upd) return upds, nil } return nil, nil } +func decodeTypedValueJSON(tv *sdcpb.TypedValue) (any, bool, error) { + var raw []byte + switch v := tv.GetValue().(type) { + case *sdcpb.TypedValue_JsonVal: + raw = v.JsonVal + case *sdcpb.TypedValue_JsonIetfVal: + raw = v.JsonIetfVal + default: + return nil, false, nil + } + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.UseNumber() + var out any + if err := dec.Decode(&out); err != nil { + return nil, true, err + } + return out, true, nil +} + func (c *Converter) ExpandUpdateKeysAsLeaf(ctx context.Context, upd *sdcpb.Update) ([]*sdcpb.Update, error) { upds := make([]*sdcpb.Update, 0) var err error diff --git a/pkg/utils/testhelper/utils.go b/pkg/utils/testhelper/utils.go index 8d170367..35aa02e5 100644 --- a/pkg/utils/testhelper/utils.go +++ b/pkg/utils/testhelper/utils.go @@ -156,3 +156,22 @@ func SplitStringSortDiff(a, b string, sep string) string { } return cmp.Diff(splits[0], splits[1]) } + +// FindBlameElement walks a BlameTreeElement path by child element names. +func FindBlameElement(elem *sdcpb.BlameTreeElement, names ...string) *sdcpb.BlameTreeElement { + cur := elem + for _, name := range names { + if cur == nil { + return nil + } + var next *sdcpb.BlameTreeElement + for _, c := range cur.GetChilds() { + if c.GetName() == name { + next = c + break + } + } + cur = next + } + return cur +} From be5f66b270e322154ef899eb11a216c735a81ac4 Mon Sep 17 00:00:00 2001 From: Markus Vahlenkamp Date: Fri, 20 Nov 2026 17:07:13 +0100 Subject: [PATCH 3/7] feat(datastore): recapture mutate-on-write revert baselines Signed-off-by: Markus Vahlenkamp --- pkg/datastore/mutate_on_write_test.go | 410 ++++++++++++++++++++++++++ pkg/datastore/sync.go | 16 +- 2 files changed, 420 insertions(+), 6 deletions(-) diff --git a/pkg/datastore/mutate_on_write_test.go b/pkg/datastore/mutate_on_write_test.go index 946d2117..74bd3666 100644 --- a/pkg/datastore/mutate_on_write_test.go +++ b/pkg/datastore/mutate_on_write_test.go @@ -339,6 +339,67 @@ func expectEmptySet(t *testing.T, sbi *mocktarget.MockTarget) *gomock.Call { }).Times(1) } +func hashedPasswordPath() *sdcpb.Path { + return &sdcpb.Path{Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("hashed-password", nil), + }} +} + +func expectHashedPasswordSetAndReadback( + t *testing.T, + f *mowDatastoreFixture, + wantCleartext string, + readback string, + onReadback func(), +) { + t.Helper() + setCall := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + DoAndReturn(func(setCtx context.Context, source targettypes.TargetSource) (*sdcpb.SetDataResponse, error) { + upds, err := source.ToProtoUpdates(setCtx, true) + if err != nil { + return nil, err + } + if got := updatesByXPath(upds)["/system/hashed-password"]; got != wantCleartext { + t.Fatalf("southbound value = %q, want %q", got, wantCleartext) + } + return &sdcpb.SetDataResponse{}, nil + }) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).After(setCall).DoAndReturn( + func(_ context.Context, req *sdcpb.GetDataRequest) (*sdcpb.GetDataResponse, error) { + if len(req.GetPath()) != 1 || req.GetPath()[0].ToXPath(false) != "/system/hashed-password" { + t.Fatalf("targeted Get paths = %v, want /system/hashed-password", req.GetPath()) + } + if onReadback != nil { + onReadback() + } + return &sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{{ + Path: hashedPasswordPath(), + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: readback}}, + }}, + }}, + }, nil + }) +} + +func assertRunningHashedPassword(t *testing.T, ds *Datastore, want string) { + t.Helper() + runningResp, err := ds.GetIntent(context.Background(), consts.RunningIntentName) + if err != nil { + t.Fatalf("GetIntent(running): %v", err) + } + runningUpds, err := runningResp.ToProtoUpdates(context.Background()) + if err != nil { + t.Fatalf("runningResp.ToProtoUpdates: %v", err) + } + if got := updatesByXPath(runningUpds)["/system/hashed-password"]; got != want { + t.Fatalf("Running hashed-password = %q, want %q", got, want) + } +} + func TestConfirmedAppliedValues_CanonicalMultiKeyPrefixSorting(t *testing.T) { store := newConfirmedAppliedValues() prefixed := &sdcpb.Path{ @@ -541,6 +602,355 @@ func TestDatastore_MutateOnWrite_SingleCommitConvergenceAndReads(t *testing.T) { } } +func TestDatastore_MutateOnWrite_RevertiveDriftRecapturesConfirmedValue(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + const ( + cleartext = "MyS3cret!" + hashV1 = "$6$salt1$hash1" + driftHash = "$6$other$hash" + hashV2 = "$6$salt2$hash2" + ) + + expectHashedPasswordSetAndReadback(t, f, cleartext, hashV1, nil) + + intent := buildJSONIntent(t, f.ds, "intent1", 10, false, map[string]any{ + "system": map[string]any{"hashed-password": cleartext}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-1", []*types.TransactionIntent{intent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet: %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-1"); err != nil { + t.Fatalf("TransactionConfirm: %v", err) + } + + expectHashedPasswordSetAndReadback(t, f, cleartext, hashV2, func() { + _, lockErr := f.ds.TransactionSet(context.Background(), "concurrent-sync-readback", nil, nil, time.Minute, false) + if !errors.Is(lockErr, ErrDatastoreLocked) { + t.Errorf("concurrent TransactionSet during sync readback returned %v, want ErrDatastoreLocked", lockErr) + } + }) + + if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{}}, jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": driftHash}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(drift): %v", err) + } + + assertRunningHashedPassword(t, f.ds, hashV2) + + if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{}}, jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": hashV2}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(converged): %v", err) + } +} + +func TestDatastore_MutateOnWrite_NonRevertiveValueDriftReportsNotApplied(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + const ( + cleartext = "MyS3cret!" + hashV1 = "$6$salt1$hash1" + driftHash = "$6$other$hash" + ) + expectHashedPasswordSetAndReadback(t, f, cleartext, hashV1, nil) + + intent := buildJSONIntent(t, f.ds, "intent1", 10, true, map[string]any{ + "system": map[string]any{"hashed-password": cleartext}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-1", []*types.TransactionIntent{intent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet: %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-1"); err != nil { + t.Fatalf("TransactionConfirm: %v", err) + } + + if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": driftHash}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(drift): %v", err) + } + + events := collectWatchDeviationsBatch(t, f.ds) + for _, ev := range events { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && + ev.GetIntent() == "intent1" && + ev.GetPath().ToXPath(false) == "/system/hashed-password" { + if ev.GetExpectedValue().GetStringVal() != cleartext || ev.GetCurrentValue().GetStringVal() != driftHash { + t.Fatalf("NOT_APPLIED expected/current = (%v, %v), want (%q, %q)", + ev.GetExpectedValue(), ev.GetCurrentValue(), cleartext, driftHash) + } + return + } + } + t.Fatalf("expected NOT_APPLIED for mutate-on-write value drift, got %v", events) +} + +func TestDatastore_MutateOnWrite_DeletedLeafDrift(t *testing.T) { + for _, tc := range []struct { + name string + nonRevertive bool + }{ + {name: "revertive intent restores and recaptures", nonRevertive: false}, + {name: "non-revertive intent reports not applied", nonRevertive: true}, + } { + t.Run(tc.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + const ( + cleartext = "MyS3cret!" + hashV1 = "$6$salt1$hash1" + hashV2 = "$6$salt2$hash2" + ) + expectHashedPasswordSetAndReadback(t, f, cleartext, hashV1, nil) + + intent := buildJSONIntent(t, f.ds, "intent1", 10, tc.nonRevertive, map[string]any{ + "system": map[string]any{"hashed-password": cleartext}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-1", []*types.TransactionIntent{intent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet: %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-1"); err != nil { + t.Fatalf("TransactionConfirm: %v", err) + } + + if !tc.nonRevertive { + expectHashedPasswordSetAndReadback(t, f, cleartext, hashV2, nil) + } + + if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hostname": "still-present"}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(delete): %v", err) + } + + if tc.nonRevertive { + events := collectWatchDeviationsBatch(t, f.ds) + found := false + for _, ev := range events { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && + ev.GetIntent() == "intent1" && + ev.GetPath().ToXPath(false) == "/system/hashed-password" { + found = true + } + } + if !found { + t.Fatalf("expected NOT_APPLIED for deleted mutate-on-write leaf, got %v", events) + } + return + } + + assertRunningHashedPassword(t, f.ds, hashV2) + if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": hashV2}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(restored deletion converged): %v", err) + } + }) + } +} + +func TestDatastore_MutateOnWrite_PriorityTakeoverAndDeletionPromotion(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + const ( + lowCleartext = "LowSecret!" + highCleartext = "HighSecret!" + hashV1 = "$6$low-epoch1$hash" + hashV2 = "$6$high-epoch$hash" + hashV3 = "$6$low-epoch2$hash" + ) + expectHashedPasswordSetAndReadback(t, f, lowCleartext, hashV1, nil) + lowIntent := buildJSONIntent(t, f.ds, "low-owner", 20, false, map[string]any{ + "system": map[string]any{"hashed-password": lowCleartext}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-low", []*types.TransactionIntent{lowIntent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(low): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-low"); err != nil { + t.Fatalf("TransactionConfirm(low): %v", err) + } + + expectHashedPasswordSetAndReadback(t, f, highCleartext, hashV2, nil) + highIntent := buildJSONIntent(t, f.ds, "high-owner", 5, false, map[string]any{ + "system": map[string]any{"hashed-password": highCleartext}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-high", []*types.TransactionIntent{highIntent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(high): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-high"); err != nil { + t.Fatalf("TransactionConfirm(high): %v", err) + } + if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": hashV2}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(high owner converged): %v", err) + } + + deleteHigh, err := f.ds.SdcpbTransactionIntentToInternalTI(ctx, &sdcpb.TransactionIntent{ + Intent: "high-owner", + Priority: 5, + Delete: true, + }) + if err != nil { + t.Fatalf("build high-owner deletion: %v", err) + } + expectHashedPasswordSetAndReadback(t, f, lowCleartext, hashV3, nil) + if _, err := f.ds.TransactionSet(ctx, "tx-delete-high", []*types.TransactionIntent{deleteHigh}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(delete high): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-delete-high"); err != nil { + t.Fatalf("TransactionConfirm(delete high): %v", err) + } + + if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": hashV3}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(promoted owner converged): %v", err) + } +} + +func TestDatastore_MutateOnWrite_UnconfirmedTransactionRollbackRecapturesPriorOwner(t *testing.T) { + for _, tc := range []struct { + name string + undo func(t *testing.T, f *mowDatastoreFixture, rollbackDone <-chan struct{}) + }{ + { + name: "TransactionCancel", + undo: func(t *testing.T, f *mowDatastoreFixture, _ <-chan struct{}) { + t.Helper() + if err := f.ds.TransactionCancel(context.Background(), "tx-change"); err != nil { + t.Fatalf("TransactionCancel: %v", err) + } + }, + }, + { + name: "rollback timer expiry", + undo: func(t *testing.T, f *mowDatastoreFixture, rollbackDone <-chan struct{}) { + t.Helper() + select { + case <-rollbackDone: + case <-time.After(3 * time.Second): + t.Fatal("timed out waiting for automatic rollback") + } + if err := f.ds.TransactionConfirm(context.Background(), "tx-change"); err == nil || + !strings.Contains(err.Error(), "no active transaction") { + t.Fatalf("TransactionConfirm after timer rollback = %v, want no active transaction", err) + } + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + const ( + oldCleartext = "OldSecret!" + newCleartext = "NewSecret!" + hashV1 = "$6$old-epoch1$hash" + hashV2 = "$6$new-epoch$hash" + hashV3 = "$6$old-epoch2$hash" + ) + expectHashedPasswordSetAndReadback(t, f, oldCleartext, hashV1, nil) + oldIntent := buildJSONIntent(t, f.ds, "owner", 10, false, map[string]any{ + "system": map[string]any{"hashed-password": oldCleartext}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-initial", []*types.TransactionIntent{oldIntent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(initial): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-initial"); err != nil { + t.Fatalf("TransactionConfirm(initial): %v", err) + } + + expectHashedPasswordSetAndReadback(t, f, newCleartext, hashV2, nil) + changedIntent := buildJSONIntent(t, f.ds, "owner", 10, false, map[string]any{ + "system": map[string]any{"hashed-password": newCleartext}, + }) + timeout := time.Minute + if tc.name == "rollback timer expiry" { + timeout = 100 * time.Millisecond + } + if _, err := f.ds.TransactionSet(ctx, "tx-change", []*types.TransactionIntent{changedIntent}, nil, timeout, false); err != nil { + t.Fatalf("TransactionSet(change): %v", err) + } + + rollbackDone := make(chan struct{}) + expectHashedPasswordSetAndReadback(t, f, oldCleartext, hashV3, func() { close(rollbackDone) }) + tc.undo(t, f, rollbackDone) + + assertRunningHashedPassword(t, f.ds, hashV3) + + if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": hashV3}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(rollback converged): %v", err) + } + }) + } +} + +func TestDatastore_MutateOnWrite_TransactionCancelRollsBackNewLeafToAbsence(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + const ( + cleartext = "NewSecret!" + hash = "$6$new$hash" + ) + expectHashedPasswordSetAndReadback(t, f, cleartext, hash, nil) + intent := buildJSONIntent(t, f.ds, "owner", 10, false, map[string]any{ + "system": map[string]any{"hashed-password": cleartext}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-new", []*types.TransactionIntent{intent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(new leaf): %v", err) + } + + f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + DoAndReturn(func(setCtx context.Context, source targettypes.TargetSource) (*sdcpb.SetDataResponse, error) { + upds, err := source.ToProtoUpdates(setCtx, true) + if err != nil { + return nil, err + } + dels, err := source.ToProtoDeletes(setCtx) + if err != nil { + return nil, err + } + if len(upds) != 0 || len(dels) != 1 { + t.Fatalf("rollback diff = updates %v, deletes %v; want one deletion and no updates", upds, dels) + } + deletePath := dels[0].ToXPath(false) + if deletePath != "/system" && deletePath != "/system/hashed-password" { + t.Fatalf("rollback delete path = %q, want hashed-password or its now-empty parent", deletePath) + } + return &sdcpb.SetDataResponse{}, nil + }) + + if err := f.ds.TransactionCancel(ctx, "tx-new"); err != nil { + t.Fatalf("TransactionCancel: %v", err) + } + assertRunningHashedPassword(t, f.ds, "") +} + func TestDatastore_MutateOnWrite_NonRepushValidationAndLeafList(t *testing.T) { ctrl := gomock.NewController(t) f := newMOWDatastoreFixture(t, ctrl) diff --git a/pkg/datastore/sync.go b/pkg/datastore/sync.go index 08c19b12..56acdf0d 100644 --- a/pkg/datastore/sync.go +++ b/pkg/datastore/sync.go @@ -146,18 +146,14 @@ func (d *Datastore) performRevert(ctx context.Context, t *tree.RootEntry) error if err != nil { return err } + updates := t.GetHighestPrecedence(true) // if we have deletes, we need to perform an apply performApply := len(del) > 0 // if no deletes, check if we have updates if !performApply { - updList, err := ops.ToProtoUpdates(ctx, t.Entry, true) - if err != nil { - return err - } - // if the update list is non-empty, we need to perform an apply - performApply = len(updList) > 0 + performApply = len(updates) > 0 } if performApply { @@ -175,6 +171,14 @@ func (d *Datastore) performRevert(ctx context.Context, t *tree.RootEntry) error resp, err := d.applyIntent(ctx, adapter.NewEntryOutputAdapter(t.Entry)) if err != nil { log.Error(err, "failed applying deviations to running", "response", utils.ProtoJSON(resp)) + return nil + } + mutateOnWritePaths := collectPushedMutateOnWritePaths(updates) + if len(mutateOnWritePaths) > 0 { + readbacks := d.fetchMutateOnWriteReadbacks(ctx, mutateOnWritePaths) + if err := d.applyReadbacksAndWriteBackRunning(ctx, updates, del, readbacks); err != nil { + return err + } } } From 5a5a179697e59c10fad38ce5e2827de64b56503b Mon Sep 17 00:00:00 2001 From: Markus Vahlenkamp Date: Fri, 20 Nov 2026 17:49:50 +0100 Subject: [PATCH 4/7] feat(datastore): add causal passive mutate-on-write capture Signed-off-by: Markus Vahlenkamp --- pkg/datastore/confirmed_applied_values.go | 105 +++++++++++++- pkg/datastore/mutate_on_write_test.go | 153 +++++++++++++++++++-- pkg/datastore/post_set_readback.go | 29 ++-- pkg/datastore/sync.go | 74 +++++++++- pkg/datastore/sync_test.go | 3 +- pkg/datastore/target/gnmi/get.go | 3 +- pkg/datastore/target/gnmi/stream.go | 64 ++++++--- pkg/datastore/target/gnmi/stream_test.go | 98 ++++++++++++- pkg/datastore/target/netconf/sync.go | 3 +- pkg/datastore/target/netconf/sync_test.go | 49 +++++++ pkg/datastore/target/types/runningstore.go | 4 +- pkg/datastore/transaction_rpc.go | 6 +- 12 files changed, 529 insertions(+), 62 deletions(-) create mode 100644 pkg/datastore/target/netconf/sync_test.go diff --git a/pkg/datastore/confirmed_applied_values.go b/pkg/datastore/confirmed_applied_values.go index 6ea12e9d..e5e224ad 100644 --- a/pkg/datastore/confirmed_applied_values.go +++ b/pkg/datastore/confirmed_applied_values.go @@ -29,9 +29,23 @@ import ( type canonicalLeafPath string type confirmedAppliedEntry struct { - owner string - intendedValue *sdcpb.TypedValue - confirmedValue *sdcpb.TypedValue + path *sdcpb.Path + owner string + intendedValue *sdcpb.TypedValue + confirmedValue *sdcpb.TypedValue + pendingCaptureAt int64 + pendingCapture bool +} + +// causalCaptureEpoch is a snapshot of one mutate-on-write write epoch. Completed +// epochs retain confirmedValue so older in-flight syncs can be ignored. +type causalCaptureEpoch struct { + path *sdcpb.Path + owner string + intendedValue *sdcpb.TypedValue + confirmedValue *sdcpb.TypedValue + captureAfterNano int64 + pending bool } // confirmedAppliedValues holds the datastore's in-memory drift baselines for @@ -59,7 +73,7 @@ func (s *confirmedAppliedValues) Lookup(path *sdcpb.Path, winningOwner string, i s.mu.RLock() entry, ok := s.entries[key] s.mu.RUnlock() - if !ok { + if !ok || entry.confirmedValue == nil { return nil } if entry.owner != winningOwner || !api.TypedValuesEqual(entry.intendedValue, intendedValue) { @@ -71,20 +85,101 @@ func (s *confirmedAppliedValues) Lookup(path *sdcpb.Path, winningOwner string, i // Record stores confirmedValue as the baseline for (path, owner, intendedValue) // when confirmedValue is a non-empty leaf value. func (s *confirmedAppliedValues) Record(path *sdcpb.Path, owner string, intendedValue, confirmedValue *sdcpb.TypedValue) { + s.record(path, owner, intendedValue, confirmedValue, 0) +} + +// RecordAfter stores a baseline and the write completion barrier that older +// in-flight sync snapshots must not cross. +func (s *confirmedAppliedValues) RecordAfter(path *sdcpb.Path, owner string, intendedValue, confirmedValue *sdcpb.TypedValue, captureAfterNano int64) { + s.record(path, owner, intendedValue, confirmedValue, captureAfterNano) +} + +func (s *confirmedAppliedValues) record(path *sdcpb.Path, owner string, intendedValue, confirmedValue *sdcpb.TypedValue, captureAfterNano int64) { if s == nil || path == nil || owner == "" || intendedValue == nil || !isNonEmptyTypedValue(confirmedValue) { return } key := newCanonicalLeafPath(path) s.mu.Lock() - s.entries[key] = confirmedAppliedEntry{ + entry := confirmedAppliedEntry{ + path: proto.Clone(path).(*sdcpb.Path), owner: owner, intendedValue: proto.Clone(intendedValue).(*sdcpb.TypedValue), confirmedValue: proto.Clone(confirmedValue).(*sdcpb.TypedValue), } + entry.pendingCaptureAt = captureAfterNano + s.entries[key] = entry + s.mu.Unlock() +} + +// MarkPending retains the winning intent identity until a causally subsequent +// sync can supply the confirmed target value. +func (s *confirmedAppliedValues) MarkPending(path *sdcpb.Path, owner string, intendedValue *sdcpb.TypedValue, captureAfterNano int64) { + if s == nil || path == nil || owner == "" || intendedValue == nil || captureAfterNano <= 0 { + return + } + key := newCanonicalLeafPath(path) + s.mu.Lock() + s.entries[key] = confirmedAppliedEntry{ + path: proto.Clone(path).(*sdcpb.Path), + owner: owner, + intendedValue: proto.Clone(intendedValue).(*sdcpb.TypedValue), + pendingCaptureAt: captureAfterNano, + pendingCapture: true, + } s.mu.Unlock() } +// CausalCaptures returns write epochs that still guard against older syncs. +// Pending entries also need the first causally subsequent observation. +func (s *confirmedAppliedValues) CausalCaptures() []causalCaptureEpoch { + if s == nil { + return nil + } + s.mu.RLock() + defer s.mu.RUnlock() + result := make([]causalCaptureEpoch, 0) + for _, entry := range s.entries { + if entry.pendingCaptureAt == 0 { + continue + } + result = append(result, causalCaptureEpoch{ + path: proto.Clone(entry.path).(*sdcpb.Path), + owner: entry.owner, + intendedValue: proto.Clone(entry.intendedValue).(*sdcpb.TypedValue), + captureAfterNano: entry.pendingCaptureAt, + pending: entry.pendingCapture, + }) + if entry.confirmedValue != nil { + result[len(result)-1].confirmedValue = proto.Clone(entry.confirmedValue).(*sdcpb.TypedValue) + } + } + return result +} + +// CompletePending binds a non-empty observation to the same pending write +// epoch, or removes that epoch when the causally subsequent sync omitted it. +func (s *confirmedAppliedValues) CompletePending(pending causalCaptureEpoch, observed *sdcpb.TypedValue) { + if s == nil { + return + } + key := newCanonicalLeafPath(pending.path) + s.mu.Lock() + defer s.mu.Unlock() + entry, ok := s.entries[key] + if !ok || !entry.pendingCapture || entry.pendingCaptureAt != pending.captureAfterNano || + entry.owner != pending.owner || !api.TypedValuesEqual(entry.intendedValue, pending.intendedValue) { + return + } + if !isNonEmptyTypedValue(observed) { + delete(s.entries, key) + return + } + entry.confirmedValue = proto.Clone(observed).(*sdcpb.TypedValue) + entry.pendingCapture = false + s.entries[key] = entry +} + // Delete removes any stored baseline for path. func (s *confirmedAppliedValues) Delete(path *sdcpb.Path) { if s == nil || path == nil { diff --git a/pkg/datastore/mutate_on_write_test.go b/pkg/datastore/mutate_on_write_test.go index 74bd3666..599a8464 100644 --- a/pkg/datastore/mutate_on_write_test.go +++ b/pkg/datastore/mutate_on_write_test.go @@ -572,7 +572,7 @@ func TestDatastore_MutateOnWrite_SingleCommitConvergenceAndReads(t *testing.T) { "hostname": hostname, }, } - if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{}}, jsonImporter.NewJsonTreeImporter(syncPayload, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, jsonImporter.NewJsonTreeImporter(syncPayload, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { t.Fatalf("ApplyToRunning: %v", err) } @@ -633,7 +633,7 @@ func TestDatastore_MutateOnWrite_RevertiveDriftRecapturesConfirmedValue(t *testi } }) - if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{}}, jsonImporter.NewJsonTreeImporter(map[string]any{ + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, jsonImporter.NewJsonTreeImporter(map[string]any{ "system": map[string]any{"hashed-password": driftHash}, }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { t.Fatalf("ApplyToRunning(drift): %v", err) @@ -641,7 +641,7 @@ func TestDatastore_MutateOnWrite_RevertiveDriftRecapturesConfirmedValue(t *testi assertRunningHashedPassword(t, f.ds, hashV2) - if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{}}, jsonImporter.NewJsonTreeImporter(map[string]any{ + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, jsonImporter.NewJsonTreeImporter(map[string]any{ "system": map[string]any{"hashed-password": hashV2}, }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { t.Fatalf("ApplyToRunning(converged): %v", err) @@ -670,7 +670,7 @@ func TestDatastore_MutateOnWrite_NonRevertiveValueDriftReportsNotApplied(t *test t.Fatalf("TransactionConfirm: %v", err) } - if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, jsonImporter.NewJsonTreeImporter(map[string]any{ "system": map[string]any{"hashed-password": driftHash}, }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { @@ -727,7 +727,7 @@ func TestDatastore_MutateOnWrite_DeletedLeafDrift(t *testing.T) { expectHashedPasswordSetAndReadback(t, f, cleartext, hashV2, nil) } - if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, jsonImporter.NewJsonTreeImporter(map[string]any{ "system": map[string]any{"hostname": "still-present"}, }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { @@ -752,7 +752,7 @@ func TestDatastore_MutateOnWrite_DeletedLeafDrift(t *testing.T) { } assertRunningHashedPassword(t, f.ds, hashV2) - if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, jsonImporter.NewJsonTreeImporter(map[string]any{ "system": map[string]any{"hashed-password": hashV2}, }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { @@ -795,7 +795,7 @@ func TestDatastore_MutateOnWrite_PriorityTakeoverAndDeletionPromotion(t *testing if err := f.ds.TransactionConfirm(ctx, "tx-high"); err != nil { t.Fatalf("TransactionConfirm(high): %v", err) } - if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, jsonImporter.NewJsonTreeImporter(map[string]any{ "system": map[string]any{"hashed-password": hashV2}, }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { @@ -818,7 +818,7 @@ func TestDatastore_MutateOnWrite_PriorityTakeoverAndDeletionPromotion(t *testing t.Fatalf("TransactionConfirm(delete high): %v", err) } - if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, jsonImporter.NewJsonTreeImporter(map[string]any{ "system": map[string]any{"hashed-password": hashV3}, }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { @@ -897,7 +897,7 @@ func TestDatastore_MutateOnWrite_UnconfirmedTransactionRollbackRecapturesPriorOw assertRunningHashedPassword(t, f.ds, hashV3) - if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{Elem: []*sdcpb.PathElem{}}}, jsonImporter.NewJsonTreeImporter(map[string]any{ "system": map[string]any{"hashed-password": hashV3}, }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { @@ -1655,7 +1655,7 @@ func TestDatastore_MutateOnWrite_DryRunAndNoopSkipTargetedGet(t *testing.T) { } // Empty readback is ignored, so an empty string in Running raises NOT_APPLIED. - if err := f.ds.ApplyToRunning(ctx, []*sdcpb.Path{{}}, jsonImporter.NewJsonTreeImporter(map[string]any{ + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, jsonImporter.NewJsonTreeImporter(map[string]any{ "system": map[string]any{"hashed-password": ""}, }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { t.Fatalf("ApplyToRunning: %v", err) @@ -1672,3 +1672,136 @@ func TestDatastore_MutateOnWrite_DryRunAndNoopSkipTargetedGet(t *testing.T) { } }) } + +func TestDatastore_MutateOnWrite_FailedReadbackUsesCausalPassiveSync(t *testing.T) { + for _, tc := range []struct { + name string + readback func() (*sdcpb.GetDataResponse, error) + }{ + { + name: "targeted Get error", + readback: func() (*sdcpb.GetDataResponse, error) { + return nil, errors.New("targeted readback unavailable") + }, + }, + { + name: "targeted Get omits requested path", + readback: func() (*sdcpb.GetDataResponse, error) { + return &sdcpb.GetDataResponse{}, nil + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + const ( + cleartext = "PendingSecret!" + staleHash = "$6$before-set$hash" + freshHash = "$6$after-set$hash" + ) + + slowSyncStartedAt := time.Now().UnixNano() + setCall := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + f.sbi.EXPECT(). + Get(gomock.Any(), gomock.Any()). + After(setCall). + DoAndReturn(func(context.Context, *sdcpb.GetDataRequest) (*sdcpb.GetDataResponse, error) { + return tc.readback() + }). + Times(1) + + intent := buildJSONIntent(t, f.ds, "intent1", 10, false, map[string]any{ + "system": map[string]any{"hashed-password": cleartext}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-pending", []*types.TransactionIntent{intent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet: %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-pending"); err != nil { + t.Fatalf("TransactionConfirm: %v", err) + } + + assertRunningHashedPassword(t, f.ds, cleartext) + + if err := f.ds.ApplyToRunning(ctx, slowSyncStartedAt, []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": staleHash}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(pre-Set slow sync): %v", err) + } + assertRunningHashedPassword(t, f.ds, cleartext) + + causalSyncStartedAt := time.Now().UnixNano() + if err := f.ds.ApplyToRunning(ctx, causalSyncStartedAt, []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": freshHash}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(post-Set sync): %v", err) + } + assertRunningHashedPassword(t, f.ds, freshHash) + + if err := f.ds.ApplyToRunning(ctx, slowSyncStartedAt, []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": staleHash}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(late pre-Set slow sync): %v", err) + } + assertRunningHashedPassword(t, f.ds, freshHash) + + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && + ev.GetPath().ToXPath(false) == "/system/hashed-password" { + t.Fatalf("unexpected NOT_APPLIED after passive capture: %v", ev) + } + } + }) + } +} + +func TestDatastore_MutateOnWrite_PendingCaptureClearsWhenCausalSyncOmitsLeaf(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + setCall := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + f.sbi.EXPECT(). + Get(gomock.Any(), gomock.Any()). + After(setCall). + Return(nil, errors.New("targeted readback unavailable")). + Times(1) + + intent := buildJSONIntent(t, f.ds, "intent1", 10, true, map[string]any{ + "system": map[string]any{"hashed-password": "MissingSecret!"}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-missing", []*types.TransactionIntent{intent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet: %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-missing"); err != nil { + t.Fatalf("TransactionConfirm: %v", err) + } + + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hostname": "still-present"}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(causal missing leaf): %v", err) + } + + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && + ev.GetIntent() == "intent1" && + ev.GetPath().ToXPath(false) == "/system/hashed-password" { + return + } + } + t.Fatal("expected NOT_APPLIED after a causal sync omitted the pending mutate-on-write leaf") +} diff --git a/pkg/datastore/post_set_readback.go b/pkg/datastore/post_set_readback.go index 59ccdb8f..0daea1f1 100644 --- a/pkg/datastore/post_set_readback.go +++ b/pkg/datastore/post_set_readback.go @@ -101,6 +101,11 @@ func (d *Datastore) fetchMutateOnWriteReadbacks(ctx context.Context, paths []*sd } } } + for _, path := range paths { + if _, ok := readbacks[newCanonicalLeafPath(path)]; !ok { + log.Info("post-Set targeted Get omitted mutate-on-write leaf", "severity", "WARN", "path", path.ToXPath(false)) + } + } return readbacks } @@ -115,15 +120,14 @@ func (d *Datastore) gnmiReadbackEncoding() (sdcpb.Encoding, bool) { return enc, true } -// applyReadbacksAndWriteBackRunning binds non-empty post-Set readbacks as -// confirmed applied values for pushed mutate-on-write leaves, evicts stale -// baselines when readbacks are empty or missing, and updates Running. -func (d *Datastore) applyReadbacksAndWriteBackRunning(ctx context.Context, updates api.LeafVariantSlice, deletes treetypes.DeleteEntriesList, readbacks map[canonicalLeafPath]*sdcpb.TypedValue) error { +// applyReadbacksAndWriteBackRunning binds non-empty post-Set readbacks and +// leaves missing values pending for causal sync capture while updating Running. +func (d *Datastore) applyReadbacksAndWriteBackRunning(ctx context.Context, updates api.LeafVariantSlice, deletes treetypes.DeleteEntriesList, readbacks map[canonicalLeafPath]*sdcpb.TypedValue, setDoneUnixNano int64) error { return d.writeReadbacksToRunning(ctx, updates, deletes, readbacks, func(le *api.LeafEntry, rb *sdcpb.TypedValue, ok bool) { if ok { - d.confirmedApplied.Record(le.SdcpbPath(), le.Owner(), le.Value(), rb) + d.confirmedApplied.RecordAfter(le.SdcpbPath(), le.Owner(), le.Value(), rb, setDoneUnixNano) } else { - d.confirmedApplied.Delete(le.SdcpbPath()) + d.confirmedApplied.MarkPending(le.SdcpbPath(), le.Owner(), le.Value(), setDoneUnixNano) } }) } @@ -131,11 +135,11 @@ func (d *Datastore) applyReadbacksAndWriteBackRunning(ctx context.Context, updat // reconcileReplaceReadbacksAndWriteBackRunning clears prior baselines after a // full-config replace, binds non-empty readbacks to matching winning persisted // owners when present, and writes confirmed applied values into Running. -func (d *Datastore) reconcileReplaceReadbacksAndWriteBackRunning(ctx context.Context, updates api.LeafVariantSlice, deletes treetypes.DeleteEntriesList, readbacks map[canonicalLeafPath]*sdcpb.TypedValue) error { +func (d *Datastore) reconcileReplaceReadbacksAndWriteBackRunning(ctx context.Context, updates api.LeafVariantSlice, deletes treetypes.DeleteEntriesList, readbacks map[canonicalLeafPath]*sdcpb.TypedValue, setDoneUnixNano int64) error { d.confirmedApplied.ClearAll() var persistedIntents *tree.RootEntry - if len(readbacks) > 0 { + if len(collectPushedMutateOnWritePaths(updates)) > 0 { if root, err := d.NewEmptyTree(ctx); err == nil { if _, loadErr := d.LoadAllButRunningIntents(ctx, root); loadErr == nil && root.FinishInsertionPhase(ctx) == nil { persistedIntents = root @@ -144,11 +148,14 @@ func (d *Datastore) reconcileReplaceReadbacksAndWriteBackRunning(ctx context.Con } return d.writeReadbacksToRunning(ctx, updates, deletes, readbacks, func(le *api.LeafEntry, rb *sdcpb.TypedValue, ok bool) { - if !ok { + owner, matched := winningPersistedOwnerWithValue(ctx, persistedIntents, le.SdcpbPath(), le.Value()) + if !matched { return } - if owner, matched := winningPersistedOwnerWithValue(ctx, persistedIntents, le.SdcpbPath(), le.Value()); matched { - d.confirmedApplied.Record(le.SdcpbPath(), owner, le.Value(), rb) + if ok { + d.confirmedApplied.RecordAfter(le.SdcpbPath(), owner, le.Value(), rb, setDoneUnixNano) + } else { + d.confirmedApplied.MarkPending(le.SdcpbPath(), owner, le.Value(), setDoneUnixNano) } }) } diff --git a/pkg/datastore/sync.go b/pkg/datastore/sync.go index 56acdf0d..71ecabed 100644 --- a/pkg/datastore/sync.go +++ b/pkg/datastore/sync.go @@ -4,6 +4,7 @@ import ( "context" "errors" "sync" + "time" "github.com/sdcio/data-server/pkg/tree" "github.com/sdcio/data-server/pkg/tree/api/adapter" @@ -15,9 +16,12 @@ import ( "github.com/sdcio/data-server/pkg/utils" "github.com/sdcio/logger" sdcpb "github.com/sdcio/sdc-protos/sdcpb" + "google.golang.org/protobuf/proto" ) -func (d *Datastore) ApplyToRunning(ctx context.Context, deletes []*sdcpb.Path, importer importer.ImportConfigAdapter) error { +// ApplyToRunning commits one sync observation. syncStartedAt is Unix +// nanoseconds captured before the producer starts reading the target snapshot. +func (d *Datastore) ApplyToRunning(ctx context.Context, syncStartedAt int64, deletes []*sdcpb.Path, importer importer.ImportConfigAdapter) error { log := logger.FromContext(ctx) @@ -84,6 +88,10 @@ func (d *Datastore) ApplyToRunning(ctx context.Context, deletes []*sdcpb.Path, i } } + if err := d.reconcilePendingCaptures(ctx, syncStartedAt, deletes); err != nil { + return err + } + // conditional trace logging if log := log.V(logger.VTrace); log.Enabled() { treeExport, err := ops.TreeExport(d.syncTree.Entry, consts.RunningIntentName, consts.RunningValuesPrio, false) @@ -120,6 +128,67 @@ func (d *Datastore) ApplyToRunning(ctx context.Context, deletes []*sdcpb.Path, i } +func (d *Datastore) reconcilePendingCaptures(ctx context.Context, syncStartedAt int64, syncPaths []*sdcpb.Path) error { + for _, pending := range d.confirmedApplied.CausalCaptures() { + if syncStartedAt < pending.captureAfterNano { + restoreValue := pending.intendedValue + if pending.confirmedValue != nil { + restoreValue = pending.confirmedValue + } + if err := d.syncTree.AddUpdatesRecursive(ctx, []*treetypes.PathAndUpdate{ + treetypes.NewPathAndUpdate( + pending.path, + treetypes.NewUpdate(nil, restoreValue, consts.RunningValuesPrio, consts.RunningIntentName, 0), + ), + }, treetypes.NewUpdateInsertFlags()); err != nil { + return err + } + continue + } + if !pending.pending { + continue + } + + var observed *sdcpb.TypedValue + wasObserved := pathCoveredBySync(pending.path, syncPaths) + entry, err := ops.NavigateSdcpbPath(ctx, d.syncTree.Entry, pending.path) + if err == nil && entry != nil { + if running := entry.GetLeafVariants().GetByOwner(consts.RunningIntentName); running != nil { + observed = running.Value() + wasObserved = wasObserved || running.GetNewFlag() || running.GetUpdateFlag() + } + } else if err != nil && !errors.Is(err, ops.ErrNavigateSdcpbPathNotFound) { + return err + } + if !wasObserved { + continue + } + d.confirmedApplied.CompletePending(pending, observed) + } + return nil +} + +func pathCoveredBySync(path *sdcpb.Path, syncPaths []*sdcpb.Path) bool { + path = canonicalPath(path) + for _, syncPath := range syncPaths { + syncPath = canonicalPath(syncPath) + if len(syncPath.GetElem()) > len(path.GetElem()) { + continue + } + covered := true + for i, elem := range syncPath.GetElem() { + if !proto.Equal(elem, path.GetElem()[i]) { + covered = false + break + } + } + if covered { + return true + } + } + return false +} + func (d *Datastore) NewEmptyTree(ctx context.Context) (*tree.RootEntry, error) { tc := d.newTreeContext() newTree, err := tree.NewTreeRoot(ctx, tc) @@ -173,10 +242,11 @@ func (d *Datastore) performRevert(ctx context.Context, t *tree.RootEntry) error log.Error(err, "failed applying deviations to running", "response", utils.ProtoJSON(resp)) return nil } + setDoneUnixNano := time.Now().UnixNano() mutateOnWritePaths := collectPushedMutateOnWritePaths(updates) if len(mutateOnWritePaths) > 0 { readbacks := d.fetchMutateOnWriteReadbacks(ctx, mutateOnWritePaths) - if err := d.applyReadbacksAndWriteBackRunning(ctx, updates, del, readbacks); err != nil { + if err := d.applyReadbacksAndWriteBackRunning(ctx, updates, del, readbacks, setDoneUnixNano); err != nil { return err } } diff --git a/pkg/datastore/sync_test.go b/pkg/datastore/sync_test.go index ddef2906..e5927ddc 100644 --- a/pkg/datastore/sync_test.go +++ b/pkg/datastore/sync_test.go @@ -7,6 +7,7 @@ import ( "runtime" "sync" "testing" + "time" "github.com/google/go-cmp/cmp" "github.com/openconfig/ygot/ygot" @@ -400,7 +401,7 @@ func TestApplyToRunning(t *testing.T) { sbi: tt.sbiFunc(ctrl), } - err := datastore.ApplyToRunning(ctx, tt.deletes, tt.importerFunc()) + err := datastore.ApplyToRunning(ctx, time.Now().UnixNano(), tt.deletes, tt.importerFunc()) if (err != nil) != tt.wantErr { t.Errorf("ApplyToRunning() error = %v, wantErr %v", err, tt.wantErr) } diff --git a/pkg/datastore/target/gnmi/get.go b/pkg/datastore/target/gnmi/get.go index e6749d8e..74e8f67a 100644 --- a/pkg/datastore/target/gnmi/get.go +++ b/pkg/datastore/target/gnmi/get.go @@ -123,6 +123,7 @@ func (s *GetSync) internalGetSync(req *sdcpb.GetDataRequest) { s.syncTreeMutex.Lock() defer s.syncTreeMutex.Unlock() + syncStartedAt := time.Now().UnixNano() // execute gnmi get resp, err := s.target.Get(s.ctx, req) if err != nil { @@ -153,7 +154,7 @@ func (s *GetSync) internalGetSync(req *sdcpb.GetDataRequest) { log.Info("sync content", "data", dsutils.ProtoJSON(result)) } - err = s.runningStore.ApplyToRunning(s.ctx, s.paths, proto.NewProtoTreeImporter(result)) + err = s.runningStore.ApplyToRunning(s.ctx, syncStartedAt, s.paths, proto.NewProtoTreeImporter(result)) if err != nil { log.Error(err, "failure importing synctree export into running") return diff --git a/pkg/datastore/target/gnmi/stream.go b/pkg/datastore/target/gnmi/stream.go index 7188bd8a..f2818083 100644 --- a/pkg/datastore/target/gnmi/stream.go +++ b/pkg/datastore/target/gnmi/stream.go @@ -141,10 +141,11 @@ func (s *StreamSync) Start() error { s.paths = append(s.paths, sp) } + syncStartedAt := time.Now().UnixNano() // start the gnmi subscribe request, that also used the pool for go s.gnmiSubscribe(subReq, updChan) // - go s.buildTreeSyncWithDatastore(updChan) + go s.buildTreeSyncWithDatastore(updChan, syncStartedAt) return nil } @@ -162,7 +163,7 @@ func (s *StreamSync) Start() error { // and being silently dropped while a slow performRevert holds the goroutine // (see GitHub issue #440). Commits still apply to Running in the order they // were started. -func (s *StreamSync) buildTreeSyncWithDatastore(cUS <-chan *NotificationData) { +func (s *StreamSync) buildTreeSyncWithDatastore(cUS <-chan *NotificationData, initialSyncStartedAt int64) { log := logger.FromContext(s.ctx) syncTree, err := s.runningStore.NewEmptyTree(s.ctx) if err != nil { @@ -189,18 +190,24 @@ func (s *StreamSync) buildTreeSyncWithDatastore(cUS <-chan *NotificationData) { // awaitingFullSync is true from a resubscribe marker until the following // SyncResponse. awaitingFullSync := false + batchStartedAt := initialSyncStartedAt // commit hands the accumulated syncTree to a background goroutine and // continues with a fresh tree. It reports false when no fresh tree could // be created. commit := func(replacePaths []*sdcpb.Path) bool { treeToCommit := syncTree + syncStartedAt := batchStartedAt + if syncStartedAt == 0 { + syncStartedAt = time.Now().UnixNano() + } next, err := s.runningStore.NewEmptyTree(s.ctx) if err != nil { log.Error(err, "failure creating new sync tree") return false } syncTree = next + batchStartedAt = 0 waitFor := prevDone done := make(chan struct{}) @@ -210,7 +217,7 @@ func (s *StreamSync) buildTreeSyncWithDatastore(cUS <-chan *NotificationData) { defer close(done) defer inflight.Add(-1) <-waitFor - if err := s.syncToRunning(treeToCommit, replacePaths, true); err != nil { + if err := s.syncToRunning(treeToCommit, syncStartedAt, replacePaths, true); err != nil { log.Error(err, "failed committing synctree to running") } }() @@ -236,6 +243,10 @@ func (s *StreamSync) buildTreeSyncWithDatastore(cUS <-chan *NotificationData) { return } awaitingFullSync = true + batchStartedAt = noti.syncStartedAt + if batchStartedAt == 0 { + batchStartedAt = time.Now().UnixNano() + } continue case markerSyncResponse: var replacePaths []*sdcpb.Path @@ -253,6 +264,12 @@ func (s *StreamSync) buildTreeSyncWithDatastore(cUS <-chan *NotificationData) { } continue } + if batchStartedAt == 0 { + batchStartedAt = noti.syncStartedAt + if batchStartedAt == 0 { + batchStartedAt = time.Now().UnixNano() + } + } err := syncTree.AddUpdatesRecursive(s.ctx, noti.updates, uif) if err != nil { log.Error(err, "failed adding update to synctree") @@ -289,11 +306,11 @@ func (s *StreamSync) gnmiSubscribe(subReq *gnmi.SubscribeRequest, updChan chan<- // sendMarker waits for all submitted notification tasks to finish, then // sends the marker. It reports false when the sync is stopping. - sendMarker := func(m notificationMarker) bool { + sendMarker := func(m notificationMarker, syncStartedAt int64) bool { taskPool.CloseAndWait() taskPool = s.vpoolFactory.NewVirtualPool(pool.VirtualTolerant) select { - case updChan <- &NotificationData{marker: m}: + case updChan <- &NotificationData{marker: m, syncStartedAt: syncStartedAt}: return true case <-s.ctx.Done(): return false @@ -302,6 +319,7 @@ func (s *StreamSync) gnmiSubscribe(subReq *gnmi.SubscribeRequest, updChan chan<- syncStartTime := time.Now() for { + syncStartedAt := time.Now().UnixNano() select { case <-s.ctx.Done(): return @@ -312,7 +330,7 @@ func (s *StreamSync) gnmiSubscribe(subReq *gnmi.SubscribeRequest, updChan chan<- if err != nil { log.Error(err, "stream sync interrupted, waiting for resubscribe") syncStartTime = time.Now() - if !sendMarker(markerResubscribed) { + if !sendMarker(markerResubscribed, syncStartTime.UnixNano()) { return } } @@ -322,14 +340,14 @@ func (s *StreamSync) gnmiSubscribe(subReq *gnmi.SubscribeRequest, updChan chan<- } switch r := resp.GetResponse().(type) { case *gnmi.SubscribeResponse_Update: - err = taskPool.Submit(newNotificationProcessorTask(resp.GetUpdate(), taskParams)) + err = taskPool.Submit(newNotificationProcessorTask(resp.GetUpdate(), taskParams, syncStartedAt)) if err != nil { log.Error(err, "failure processing notifications") continue } case *gnmi.SubscribeResponse_SyncResponse: log.Info("SyncResponse flag received", "initial sync duration", time.Since(syncStartTime).String()) - if !sendMarker(markerSyncResponse) { + if !sendMarker(markerSyncResponse, 0) { return } @@ -351,7 +369,7 @@ func (s *StreamSync) gnmiSubscribe(subReq *gnmi.SubscribeRequest, updChan chan<- // // replacePaths are deleted from Running before the import, so Running under // those paths ends up equal to syncTree. An empty syncTree still applies them. -func (s *StreamSync) syncToRunning(syncTree *tree.RootEntry, replacePaths []*sdcpb.Path, logCount bool) error { +func (s *StreamSync) syncToRunning(syncTree *tree.RootEntry, syncStartedAt int64, replacePaths []*sdcpb.Path, logCount bool) error { log := logger.FromContext(s.ctx) startTime := time.Now() @@ -364,7 +382,7 @@ func (s *StreamSync) syncToRunning(syncTree *tree.RootEntry, replacePaths []*sdc return nil } log.Info("sync found no config under the synced paths, clearing them in running") - return s.runningStore.ApplyToRunning(s.ctx, replacePaths, nil) + return s.runningStore.ApplyToRunning(s.ctx, syncStartedAt, replacePaths, nil) } log.Error(err, "sync tree export error") return err @@ -380,7 +398,7 @@ func (s *StreamSync) syncToRunning(syncTree *tree.RootEntry, replacePaths []*sdc log.V(logger.VTrace).Info("synctree export done", "duration", time.Since(startTime).String()) startTime = time.Now() - err = s.runningStore.ApplyToRunning(s.ctx, deletes, proto.NewProtoTreeImporter(result)) + err = s.runningStore.ApplyToRunning(s.ctx, syncStartedAt, deletes, proto.NewProtoTreeImporter(result)) if err != nil { log.Error(err, "failed importing sync to running") return err @@ -408,14 +426,16 @@ const ( ) type NotificationData struct { - updates []*treetypes.PathAndUpdate - deletes *sdcpb.PathSet - marker notificationMarker + updates []*treetypes.PathAndUpdate + deletes *sdcpb.PathSet + marker notificationMarker + syncStartedAt int64 } type notificationProcessorTask struct { - item *gnmi.Notification - params *NotificationProcessorTaskParameters + item *gnmi.Notification + params *NotificationProcessorTaskParameters + syncStartedAt int64 } type NotificationProcessorTaskParameters struct { @@ -432,10 +452,11 @@ func NewNotificationProcessorTaskParameters(notificationResult chan<- *Notificat } } -func newNotificationProcessorTask(item *gnmi.Notification, params *NotificationProcessorTaskParameters) *notificationProcessorTask { +func newNotificationProcessorTask(item *gnmi.Notification, params *NotificationProcessorTaskParameters, syncStartedAt int64) *notificationProcessorTask { return ¬ificationProcessorTask{ - item: item, - params: params, + item: item, + params: params, + syncStartedAt: syncStartedAt, } } @@ -474,7 +495,8 @@ func (t *notificationProcessorTask) Run(ctx context.Context, _ func(pool.Task) e } return t.sendNotificationData(ctx, &NotificationData{ - updates: upds, - deletes: deletes, + updates: upds, + deletes: deletes, + syncStartedAt: t.syncStartedAt, }) } diff --git a/pkg/datastore/target/gnmi/stream_test.go b/pkg/datastore/target/gnmi/stream_test.go index 72253178..934a5010 100644 --- a/pkg/datastore/target/gnmi/stream_test.go +++ b/pkg/datastore/target/gnmi/stream_test.go @@ -10,8 +10,8 @@ import ( "time" "github.com/openconfig/gnmi/proto/gnmi" - schemaClientPkg "github.com/sdcio/data-server/pkg/datastore/clients/schema" "github.com/sdcio/data-server/pkg/config" + schemaClientPkg "github.com/sdcio/data-server/pkg/datastore/clients/schema" "github.com/sdcio/data-server/pkg/pool" "github.com/sdcio/data-server/pkg/tree" treeimporter "github.com/sdcio/data-server/pkg/tree/importer" @@ -35,13 +35,16 @@ type fakeRunningStore struct { mu sync.Mutex deletesSeen [][]*sdcpb.Path importSeen []bool + startedSeen []int64 } // applied returns a snapshot of the deletes and importer-presence of every completed ApplyToRunning call. -func (f *fakeRunningStore) applied() ([][]*sdcpb.Path, []bool) { +func (f *fakeRunningStore) applied() ([][]*sdcpb.Path, []bool, []int64) { f.mu.Lock() defer f.mu.Unlock() - return append([][]*sdcpb.Path(nil), f.deletesSeen...), append([]bool(nil), f.importSeen...) + return append([][]*sdcpb.Path(nil), f.deletesSeen...), + append([]bool(nil), f.importSeen...), + append([]int64(nil), f.startedSeen...) } func newFakeRunningStore(sc *schemaClientPkg.SchemaClientBoundImpl, vp pool.VirtualPoolFactory) *fakeRunningStore { @@ -53,7 +56,7 @@ func newFakeRunningStore(sc *schemaClientPkg.SchemaClientBoundImpl, vp pool.Virt } } -func (f *fakeRunningStore) ApplyToRunning(ctx context.Context, deletes []*sdcpb.Path, imp treeimporter.ImportConfigAdapter) error { +func (f *fakeRunningStore) ApplyToRunning(ctx context.Context, syncStartedAt int64, deletes []*sdcpb.Path, imp treeimporter.ImportConfigAdapter) error { f.firstStartedOnce.Do(func() { close(f.firstStarted) }) select { case <-f.firstUnblock: @@ -63,6 +66,7 @@ func (f *fakeRunningStore) ApplyToRunning(ctx context.Context, deletes []*sdcpb. f.mu.Lock() f.deletesSeen = append(f.deletesSeen, deletes) f.importSeen = append(f.importSeen, imp != nil) + f.startedSeen = append(f.startedSeen, syncStartedAt) f.mu.Unlock() f.calls.Add(1) return nil @@ -83,6 +87,14 @@ func (f *fakeSyncTarget) Subscribe(_ context.Context, _ *gnmi.SubscribeRequest, return f.respChan, f.errChan } +type fakeGetTarget struct { + response *sdcpb.GetDataResponse +} + +func (f *fakeGetTarget) Get(context.Context, *sdcpb.GetDataRequest) (*sdcpb.GetDataResponse, error) { + return f.response, nil +} + // interfaceDescriptionNotif returns a gNMI SubscribeResponse_Update for // /interface[name=ifname]/description = desc. func interfaceDescriptionNotif(ifname, desc string) *gnmi.SubscribeResponse { @@ -268,8 +280,8 @@ type failAfterFirstNewEmptyTree struct { calls atomic.Int32 } -func (f *failAfterFirstNewEmptyTree) ApplyToRunning(ctx context.Context, d []*sdcpb.Path, i treeimporter.ImportConfigAdapter) error { - return f.inner.ApplyToRunning(ctx, d, i) +func (f *failAfterFirstNewEmptyTree) ApplyToRunning(ctx context.Context, syncStartedAt int64, d []*sdcpb.Path, i treeimporter.ImportConfigAdapter) error { + return f.inner.ApplyToRunning(ctx, syncStartedAt, d, i) } func (f *failAfterFirstNewEmptyTree) NewEmptyTree(ctx context.Context) (*tree.RootEntry, error) { @@ -317,6 +329,70 @@ func newStreamSyncForTest(t *testing.T, ctx context.Context, paths []string) (*S return ss, target, store } +func TestGetSync_PassesSnapshotStartToRunning(t *testing.T) { + ctx := context.Background() + sc, schemaConf, err := testhelper.InitSDCIOSchema() + if err != nil { + t.Fatalf("init schema: %v", err) + } + scb := schemaClientPkg.NewSchemaClientBound(schemaConf, sc) + sharedPool := pool.NewSharedTaskPool(ctx, runtime.GOMAXPROCS(0)) + store := newFakeRunningStore(scb, sharedPool) + close(store.firstUnblock) + + target := &fakeGetTarget{response: &sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("interface", map[string]string{"name": "ethernet-1/1"}), + sdcpb.NewPathElem("description", nil), + }}, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: "from-get"}}, + }}, + }}, + }} + syncer, err := NewGetSync(ctx, target, &config.SyncProtocol{ + Name: "get-sync", + Paths: []string{"/interface"}, + }, store, scb) + if err != nil { + t.Fatalf("NewGetSync: %v", err) + } + + before := time.Now().UnixNano() + syncer.internalGetSync(&sdcpb.GetDataRequest{}) + after := time.Now().UnixNano() + + _, _, started := store.applied() + if len(started) != 1 || started[0] < before || started[0] > after { + t.Fatalf("syncStartedAt=%v, want one timestamp in [%d,%d]", started, before, after) + } +} + +func TestNotificationProcessor_PreservesPreQueueStartTime(t *testing.T) { + ctx := context.Background() + sc, schemaConf, err := testhelper.InitSDCIOSchema() + if err != nil { + t.Fatalf("init schema: %v", err) + } + scb := schemaClientPkg.NewSchemaClientBound(schemaConf, sc) + result := make(chan *NotificationData, 1) + const syncStartedAt = int64(123456789) + noti := interfaceDescriptionNotif("ethernet-1/1", "queued").GetUpdate() + + task := newNotificationProcessorTask( + noti, + NewNotificationProcessorTaskParameters(result, scb, time.Second), + syncStartedAt, + ) + if err := task.Run(ctx, nil); err != nil { + t.Fatalf("Run: %v", err) + } + if got := (<-result).syncStartedAt; got != syncStartedAt { + t.Fatalf("syncStartedAt=%d, want pre-queue timestamp %d", got, syncStartedAt) + } +} + func waitForApplyCalls(t *testing.T, store *fakeRunningStore, want int32) { t.Helper() deadline := time.Now().Add(10 * time.Second) @@ -371,7 +447,7 @@ func TestStreamSync_ResubscribeReplacesSyncedPaths(t *testing.T) { target.respChan <- syncRespMsg() waitForApplyCalls(t, store, 3) - deletes, imported := store.applied() + deletes, imported, started := store.applied() if len(deletes) != 3 { t.Fatalf("got %d ApplyToRunning calls, want 3", len(deletes)) } @@ -390,4 +466,12 @@ func TestStreamSync_ResubscribeReplacesSyncedPaths(t *testing.T) { if !imported[2] { t.Errorf("resync with device config must import it") } + for i, syncStartedAt := range started { + if syncStartedAt <= 0 { + t.Errorf("sync %d: syncStartedAt=%d, want a timestamp captured before the snapshot", i, syncStartedAt) + } + if i > 0 && syncStartedAt <= started[i-1] { + t.Errorf("sync %d: syncStartedAt=%d, want later than previous snapshot %d", i, syncStartedAt, started[i-1]) + } + } } diff --git a/pkg/datastore/target/netconf/sync.go b/pkg/datastore/target/netconf/sync.go index 075b7676..f2220443 100644 --- a/pkg/datastore/target/netconf/sync.go +++ b/pkg/datastore/target/netconf/sync.go @@ -108,13 +108,14 @@ func (s *NetconfSyncImpl) syncConfig() (*sdcpb.GetDataRequest, error) { } func (s *NetconfSyncImpl) internalSync(req *sdcpb.GetDataRequest) error { + syncStartedAt := time.Now().UnixNano() // execute netconf get importer, err := s.target.GetImportAdapter(s.ctx, req) if err != nil { return err } - return s.runningStore.ApplyToRunning(s.ctx, s.paths, importer) + return s.runningStore.ApplyToRunning(s.ctx, syncStartedAt, s.paths, importer) } func (s *NetconfSyncImpl) Stop() error { diff --git a/pkg/datastore/target/netconf/sync_test.go b/pkg/datastore/target/netconf/sync_test.go new file mode 100644 index 00000000..efa6d88d --- /dev/null +++ b/pkg/datastore/target/netconf/sync_test.go @@ -0,0 +1,49 @@ +package netconf + +import ( + "context" + "testing" + "time" + + "github.com/sdcio/data-server/pkg/tree" + "github.com/sdcio/data-server/pkg/tree/importer" + sdcpb "github.com/sdcio/sdc-protos/sdcpb" +) + +type timestampRunningStore struct { + syncStartedAt int64 +} + +func (s *timestampRunningStore) ApplyToRunning(_ context.Context, syncStartedAt int64, _ []*sdcpb.Path, _ importer.ImportConfigAdapter) error { + s.syncStartedAt = syncStartedAt + return nil +} + +func (*timestampRunningStore) NewEmptyTree(context.Context) (*tree.RootEntry, error) { + return nil, nil +} + +type staticXMLImporterTarget struct{} + +func (staticXMLImporterTarget) GetImportAdapter(context.Context, *sdcpb.GetDataRequest) (importer.ImportConfigAdapter, error) { + return nil, nil +} + +func TestNetconfSync_PassesSnapshotStartToRunning(t *testing.T) { + store := ×tampRunningStore{} + syncer := &NetconfSyncImpl{ + ctx: context.Background(), + target: staticXMLImporterTarget{}, + runningStore: store, + } + + before := time.Now().UnixNano() + if err := syncer.internalSync(&sdcpb.GetDataRequest{}); err != nil { + t.Fatalf("internalSync: %v", err) + } + after := time.Now().UnixNano() + + if store.syncStartedAt < before || store.syncStartedAt > after { + t.Fatalf("syncStartedAt=%d, want timestamp in [%d,%d]", store.syncStartedAt, before, after) + } +} diff --git a/pkg/datastore/target/types/runningstore.go b/pkg/datastore/target/types/runningstore.go index 5b9836fd..02c33452 100644 --- a/pkg/datastore/target/types/runningstore.go +++ b/pkg/datastore/target/types/runningstore.go @@ -9,6 +9,8 @@ import ( ) type RunningStore interface { - ApplyToRunning(ctx context.Context, deletes []*sdcpb.Path, importer importer.ImportConfigAdapter) error + // ApplyToRunning commits a sync observation whose Unix-nanosecond start + // timestamp was captured before the producer began reading the target. + ApplyToRunning(ctx context.Context, syncStartedAt int64, deletes []*sdcpb.Path, importer importer.ImportConfigAdapter) error NewEmptyTree(ctx context.Context) (*tree.RootEntry, error) } diff --git a/pkg/datastore/transaction_rpc.go b/pkg/datastore/transaction_rpc.go index 1b7c6152..9a343a28 100644 --- a/pkg/datastore/transaction_rpc.go +++ b/pkg/datastore/transaction_rpc.go @@ -144,6 +144,7 @@ func (d *Datastore) replaceIntent(ctx context.Context, transaction *types.Transa if err != nil { return nil, err } + setDoneUnixNano := time.Now().UnixNano() // collect warnings warnings = append(warnings, dataResp.GetWarnings()...) @@ -154,7 +155,7 @@ func (d *Datastore) replaceIntent(ctx context.Context, transaction *types.Transa deletes := treetypes.DeleteEntriesList{root} readbacks := d.fetchMutateOnWriteReadbacks(ctx, collectPushedMutateOnWritePaths(updates)) - err = d.reconcileReplaceReadbacksAndWriteBackRunning(ctx, updates, deletes, readbacks) + err = d.reconcileReplaceReadbacksAndWriteBackRunning(ctx, updates, deletes, readbacks, setDoneUnixNano) if err != nil { return nil, err } @@ -335,6 +336,7 @@ func (d *Datastore) lowlevelTransactionSet(ctx context.Context, transaction *typ if err != nil { return nil, err } + setDoneUnixNano := time.Now().UnixNano() result.Warnings = append(result.Warnings, dataResp.GetWarnings()...) readbacks := d.fetchMutateOnWriteReadbacks(ctx, collectPushedMutateOnWritePaths(updates)) @@ -380,7 +382,7 @@ func (d *Datastore) lowlevelTransactionSet(ctx context.Context, transaction *typ } } - err = d.applyReadbacksAndWriteBackRunning(ctx, updates, deletes, readbacks) + err = d.applyReadbacksAndWriteBackRunning(ctx, updates, deletes, readbacks, setDoneUnixNano) if err != nil { return nil, err } From 1b0b0139fb591345bee08718d94d77b75dcb5d6c Mon Sep 17 00:00:00 2001 From: Markus Vahlenkamp Date: Fri, 20 Nov 2026 20:02:27 +0100 Subject: [PATCH 5/7] feat(datastore,tree): discover crypt-mutated unannotated string leaves Signed-off-by: Markus Vahlenkamp --- pkg/datastore/confirmed_applied_values.go | 213 ++++- pkg/datastore/mutate_on_write_test.go | 856 ++++++++++++++++++ pkg/datastore/post_set_readback.go | 129 ++- pkg/datastore/sync.go | 105 ++- pkg/datastore/transaction_rpc.go | 4 +- pkg/tree/api/tree_context.go | 23 + .../ops/validation/validation_dispatch.go | 2 +- pkg/tree/tree_context.go | 33 +- 8 files changed, 1272 insertions(+), 93 deletions(-) diff --git a/pkg/datastore/confirmed_applied_values.go b/pkg/datastore/confirmed_applied_values.go index e5e224ad..c3270633 100644 --- a/pkg/datastore/confirmed_applied_values.go +++ b/pkg/datastore/confirmed_applied_values.go @@ -18,6 +18,7 @@ import ( "slices" "strings" "sync" + "unicode" "github.com/sdcio/data-server/pkg/tree/api" sdcpb "github.com/sdcio/sdc-protos/sdcpb" @@ -28,13 +29,25 @@ import ( // shared across tree lookups and southbound readbacks. type canonicalLeafPath string +// keylessLeafPath is the module-prefix-stripped, key-pruned XPath identifier +// for a leaf's schema path across all list instances. +type keylessLeafPath string + +type captureMode uint8 + +const ( + captureConfirmed captureMode = iota + capturePendingMutateOnWrite + capturePendingCryptDiscovery +) + type confirmedAppliedEntry struct { path *sdcpb.Path owner string intendedValue *sdcpb.TypedValue confirmedValue *sdcpb.TypedValue pendingCaptureAt int64 - pendingCapture bool + mode captureMode } // causalCaptureEpoch is a snapshot of one mutate-on-write write epoch. Completed @@ -45,20 +58,26 @@ type causalCaptureEpoch struct { intendedValue *sdcpb.TypedValue confirmedValue *sdcpb.TypedValue captureAfterNano int64 - pending bool + mode captureMode } -// confirmedAppliedValues holds the datastore's in-memory drift baselines for -// mutate-on-write leaves, keyed by canonicalLeafPath and bound to (owner, intendedValue). +func (e causalCaptureEpoch) IsPending() bool { + return e.mode != captureConfirmed +} + +// confirmedAppliedValues holds the datastore's in-memory drift baselines and +// dynamically learned keyless schema paths for mutate-on-write leaves. // Entries live strictly in process memory and are never written to cache storage. type confirmedAppliedValues struct { - mu sync.RWMutex - entries map[canonicalLeafPath]confirmedAppliedEntry + mu sync.RWMutex + entries map[canonicalLeafPath]confirmedAppliedEntry + learnedPaths map[keylessLeafPath]struct{} } func newConfirmedAppliedValues() *confirmedAppliedValues { return &confirmedAppliedValues{ - entries: make(map[canonicalLeafPath]confirmedAppliedEntry), + entries: make(map[canonicalLeafPath]confirmedAppliedEntry), + learnedPaths: make(map[keylessLeafPath]struct{}), } } @@ -83,13 +102,15 @@ func (s *confirmedAppliedValues) Lookup(path *sdcpb.Path, winningOwner string, i } // Record stores confirmedValue as the baseline for (path, owner, intendedValue) -// when confirmedValue is a non-empty leaf value. +// when confirmedValue is non-empty. If intendedValue already matches the +// crypt/cipher allowlist and confirmedValue differs, any baseline for path is evicted. func (s *confirmedAppliedValues) Record(path *sdcpb.Path, owner string, intendedValue, confirmedValue *sdcpb.TypedValue) { s.record(path, owner, intendedValue, confirmedValue, 0) } // RecordAfter stores a baseline and the write completion barrier that older -// in-flight sync snapshots must not cross. +// in-flight sync snapshots must not cross, or evicts any baseline for path when +// a pre-hashed intendedValue differs from confirmedValue. func (s *confirmedAppliedValues) RecordAfter(path *sdcpb.Path, owner string, intendedValue, confirmedValue *sdcpb.TypedValue, captureAfterNano int64) { s.record(path, owner, intendedValue, confirmedValue, captureAfterNano) } @@ -98,16 +119,21 @@ func (s *confirmedAppliedValues) record(path *sdcpb.Path, owner string, intended if s == nil || path == nil || owner == "" || intendedValue == nil || !isNonEmptyTypedValue(confirmedValue) { return } + if rejectsPreHashedMismatch(intendedValue, confirmedValue) { + s.Delete(path) + return + } key := newCanonicalLeafPath(path) s.mu.Lock() entry := confirmedAppliedEntry{ - path: proto.Clone(path).(*sdcpb.Path), - owner: owner, - intendedValue: proto.Clone(intendedValue).(*sdcpb.TypedValue), - confirmedValue: proto.Clone(confirmedValue).(*sdcpb.TypedValue), + path: proto.Clone(path).(*sdcpb.Path), + owner: owner, + intendedValue: proto.Clone(intendedValue).(*sdcpb.TypedValue), + confirmedValue: proto.Clone(confirmedValue).(*sdcpb.TypedValue), + pendingCaptureAt: captureAfterNano, + mode: captureConfirmed, } - entry.pendingCaptureAt = captureAfterNano s.entries[key] = entry s.mu.Unlock() } @@ -115,6 +141,16 @@ func (s *confirmedAppliedValues) record(path *sdcpb.Path, owner string, intended // MarkPending retains the winning intent identity until a causally subsequent // sync can supply the confirmed target value. func (s *confirmedAppliedValues) MarkPending(path *sdcpb.Path, owner string, intendedValue *sdcpb.TypedValue, captureAfterNano int64) { + s.markPending(path, owner, intendedValue, captureAfterNano, capturePendingMutateOnWrite) +} + +// MarkDiscoveryCandidate records an unconfirmed push marker for an unannotated +// plain string leaf whose first causal sync may reveal a crypt or cipher value. +func (s *confirmedAppliedValues) MarkDiscoveryCandidate(path *sdcpb.Path, owner string, intendedValue *sdcpb.TypedValue, captureAfterNano int64) { + s.markPending(path, owner, intendedValue, captureAfterNano, capturePendingCryptDiscovery) +} + +func (s *confirmedAppliedValues) markPending(path *sdcpb.Path, owner string, intendedValue *sdcpb.TypedValue, captureAfterNano int64, mode captureMode) { if s == nil || path == nil || owner == "" || intendedValue == nil || captureAfterNano <= 0 { return } @@ -125,7 +161,7 @@ func (s *confirmedAppliedValues) MarkPending(path *sdcpb.Path, owner string, int owner: owner, intendedValue: proto.Clone(intendedValue).(*sdcpb.TypedValue), pendingCaptureAt: captureAfterNano, - pendingCapture: true, + mode: mode, } s.mu.Unlock() } @@ -148,7 +184,7 @@ func (s *confirmedAppliedValues) CausalCaptures() []causalCaptureEpoch { owner: entry.owner, intendedValue: proto.Clone(entry.intendedValue).(*sdcpb.TypedValue), captureAfterNano: entry.pendingCaptureAt, - pending: entry.pendingCapture, + mode: entry.mode, }) if entry.confirmedValue != nil { result[len(result)-1].confirmedValue = proto.Clone(entry.confirmedValue).(*sdcpb.TypedValue) @@ -157,29 +193,60 @@ func (s *confirmedAppliedValues) CausalCaptures() []causalCaptureEpoch { return result } -// CompletePending binds a non-empty observation to the same pending write -// epoch, or removes that epoch when the causally subsequent sync omitted it. +// CompletePending resolves pending against the first causally subsequent +// observation: crypt-discovery epochs bind matching crypt/cipher observations +// and permanently learn the leaf's keyless schema path, mutate-on-write epochs +// bind non-empty observations unless a pre-hashed intendedValue differs, and +// non-matching or missing observations evict the epoch. func (s *confirmedAppliedValues) CompletePending(pending causalCaptureEpoch, observed *sdcpb.TypedValue) { - if s == nil { + if s == nil || !pending.IsPending() { return } key := newCanonicalLeafPath(pending.path) s.mu.Lock() defer s.mu.Unlock() entry, ok := s.entries[key] - if !ok || !entry.pendingCapture || entry.pendingCaptureAt != pending.captureAfterNano || + if !ok || entry.mode != pending.mode || entry.pendingCaptureAt != pending.captureAfterNano || entry.owner != pending.owner || !api.TypedValuesEqual(entry.intendedValue, pending.intendedValue) { return } - if !isNonEmptyTypedValue(observed) { + if pending.mode == capturePendingCryptDiscovery { + if !isCryptDiscoveryMatch(pending.intendedValue, observed) { + delete(s.entries, key) + return + } + entry.confirmedValue = proto.Clone(observed).(*sdcpb.TypedValue) + entry.mode = captureConfirmed + s.entries[key] = entry + if kp := newKeylessLeafPath(pending.path); kp != "" { + s.learnedPaths[kp] = struct{}{} + } + return + } + if !isNonEmptyTypedValue(observed) || rejectsPreHashedMismatch(pending.intendedValue, observed) { delete(s.entries, key) return } entry.confirmedValue = proto.Clone(observed).(*sdcpb.TypedValue) - entry.pendingCapture = false + entry.mode = captureConfirmed s.entries[key] = entry } +// DeleteSubtree removes stored baselines or pending markers at or below prefix. +func (s *confirmedAppliedValues) DeleteSubtree(prefix *sdcpb.Path) { + if s == nil || prefix == nil { + return + } + prefixSlices := []*sdcpb.Path{prefix} + s.mu.Lock() + for key, entry := range s.entries { + if pathCoveredBySync(entry.path, prefixSlices) { + delete(s.entries, key) + } + } + s.mu.Unlock() +} + // Delete removes any stored baseline for path. func (s *confirmedAppliedValues) Delete(path *sdcpb.Path) { if s == nil || path == nil { @@ -201,7 +268,33 @@ func (s *confirmedAppliedValues) ClearAll() { s.mu.Unlock() } -var _ api.ConfirmedAppliedValueResolver = (*confirmedAppliedValues)(nil) +var ( + _ api.ConfirmedAppliedValueResolver = (*confirmedAppliedValues)(nil) + _ api.LearnedMutateOnWritePathSet = (*confirmedAppliedValues)(nil) +) + +// IsLearnedMutateOnWritePath reports whether path's keyless schema path was +// dynamically learned as a mutate-on-write leaf on this datastore. +func (s *confirmedAppliedValues) IsLearnedMutateOnWritePath(path *sdcpb.Path) bool { + if s == nil { + return false + } + kp := newKeylessLeafPath(path) + if kp == "" { + return false + } + s.mu.RLock() + _, ok := s.learnedPaths[kp] + s.mu.RUnlock() + return ok +} + +func newKeylessLeafPath(p *sdcpb.Path) keylessLeafPath { + if p == nil || len(p.GetElem()) == 0 { + return "" + } + return keylessLeafPath(canonicalPath(p).ToXPath(true)) +} func stripModulePrefix(name string) string { if _, local, ok := strings.Cut(name, ":"); ok { @@ -296,3 +389,77 @@ func isNonEmptyTypedValue(tv *sdcpb.TypedValue) bool { return true } } + +var dollarCryptPrefixes = []string{ + "$1$", + "$2a$", + "$2b$", + "$2x$", + "$2y$", + "$5$", + "$6$", + "$7$", + "$8$", + "$9$", + "$y$", + "$gy$", + "$ar2$", + "$argon2i$", + "$argon2id$", + "$scrypt$", + "$sha1$", +} + +func containsWhitespace(s string) bool { + return strings.IndexFunc(s, unicode.IsSpace) >= 0 +} + +// isCryptOrCipherString reports whether s matches the strict crypt or +// passphrase format allowlist used to identify target-hashed string secrets. +func isCryptOrCipherString(s string) bool { + if s == "" { + return false + } + for _, suffix := range []string{" hash2", " hash"} { + if token, ok := strings.CutSuffix(s, suffix); ok { + return token != "" && !containsWhitespace(token) + } + } + if containsWhitespace(s) { + return false + } + if strings.HasPrefix(s, "000PASSPHRASE000") { + return true + } + for _, prefix := range dollarCryptPrefixes { + if strings.HasPrefix(s, prefix) { + return len(s) > len(prefix) + } + } + if rest, ok := strings.CutPrefix(s, "$pbkdf2"); ok { + if strings.HasPrefix(rest, "$") { + return len(rest) > 1 + } + if strings.HasPrefix(rest, "-") { + alg, tail, hasDollar := strings.Cut(rest[1:], "$") + return hasDollar && alg != "" && tail != "" + } + } + return false +} + +func matchesCryptOrCipherValue(tv *sdcpb.TypedValue) bool { + sv, ok := tv.GetValue().(*sdcpb.TypedValue_StringVal) + return ok && isCryptOrCipherString(sv.StringVal) +} + +func rejectsPreHashedMismatch(intendedValue, observed *sdcpb.TypedValue) bool { + return matchesCryptOrCipherValue(intendedValue) && !api.TypedValuesEqual(observed, intendedValue) +} + +func isCryptDiscoveryMatch(intendedValue, observed *sdcpb.TypedValue) bool { + if !isNonEmptyTypedValue(observed) || api.TypedValuesEqual(observed, intendedValue) { + return false + } + return !matchesCryptOrCipherValue(intendedValue) && matchesCryptOrCipherValue(observed) +} diff --git a/pkg/datastore/mutate_on_write_test.go b/pkg/datastore/mutate_on_write_test.go index 599a8464..eafe4d26 100644 --- a/pkg/datastore/mutate_on_write_test.go +++ b/pkg/datastore/mutate_on_write_test.go @@ -107,6 +107,11 @@ func initMutateOnWriteSchema(t *testing.T) (schema.Client, *config.SchemaConfig) leaf password { type ianach:crypt-hash; } + leaf secret { + type string { + length "4..32"; + } + } } } } @@ -1805,3 +1810,854 @@ func TestDatastore_MutateOnWrite_PendingCaptureClearsWhenCausalSyncOmitsLeaf(t * } t.Fatal("expected NOT_APPLIED after a causal sync omitted the pending mutate-on-write leaf") } + +func TestDatastore_MutateOnWrite_UnannotatedStringCryptDiscovery(t *testing.T) { + for _, tc := range []struct { + name string + targetVal string + }{ + {name: "md5 $1$", targetVal: "$1$saltsalt$abcdefghijklmnopqrstuv"}, + {name: "bcrypt $2a$", targetVal: "$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy"}, + {name: "bcrypt $2b$", targetVal: "$2b$12$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy"}, + {name: "bcrypt $2x$", targetVal: "$2x$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy"}, + {name: "bcrypt $2y$", targetVal: "$2y$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy"}, + {name: "sha256 $5$", targetVal: "$5$rounds=5000$saltsalt$hashed256value"}, + {name: "sha512 $6$", targetVal: "$6$rounds=5000$saltsalt$hashed512value"}, + {name: "scrypt mcf $7$", targetVal: "$7$CU..../....$salt$hashedvalue"}, + {name: "type8 $8$", targetVal: "$8$dsYGNam3K1SIJO$7nv/35M2qr6t.dVc7UY9zrX"}, + {name: "type9/junos $9$", targetVal: "$9$1k2j3h4g5f6d7s8a"}, + {name: "yescrypt $y$", targetVal: "$y$j9T$salt$hashedvalue"}, + {name: "gost-yescrypt $gy$", targetVal: "$gy$j9T$salt$hashedvalue"}, + {name: "ar2 $ar2$", targetVal: "$ar2$v=19$salt$hashedvalue"}, + {name: "argon2i $argon2i$", targetVal: "$argon2i$v=19$m=4096,t=3,p=1$c2FsdA$aGFzaA"}, + {name: "argon2id $argon2id$", targetVal: "$argon2id$v=19$m=65536,t=3,p=4$c2FsdA$aGFzaA"}, + {name: "pbkdf2 $pbkdf2$", targetVal: "$pbkdf2$1000$c2FsdA$aGFzaA"}, + {name: "pbkdf2-sha256 $pbkdf2-sha256$", targetVal: "$pbkdf2-sha256$29000$c2FsdA$aGFzaA"}, + {name: "scrypt $scrypt$", targetVal: "$scrypt$ln=16,r=8,p=1$c2FsdA$aGFzaA"}, + {name: "sha1 $sha1$", targetVal: "$sha1$40000$saltsalt$hashedsha1value"}, + {name: "passphrase prefix 000PASSPHRASE000", targetVal: "000PASSPHRASE000dGVzdGNpcGhlcnRleHQ="}, + {name: "passphrase sentinel 000PASSPHRASE000", targetVal: "000PASSPHRASE000"}, + {name: "sros token hash", targetVal: "dGhpcyBpcyBhIHRlc3Q= hash"}, + {name: "sros token hash2", targetVal: "dGhpcyBpcyBhIHRlc3Q= hash2"}, + } { + t.Run(tc.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + const cleartext = "KeychainSecret1" + + slowSyncStartedAt := time.Now().UnixNano() + f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + + intent := buildJSONIntent(t, f.ds, "intent1", 10, false, map[string]any{ + "system": map[string]any{ + "user": []any{map[string]any{ + "username": "alice", + "secret": cleartext, + }}, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-discover", []*types.TransactionIntent{intent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet: %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-discover"); err != nil { + t.Fatalf("TransactionConfirm: %v", err) + } + + // Slow pre-Set sync must not revert or bind stale data. + if err := f.ds.ApplyToRunning(ctx, slowSyncStartedAt, []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "user": []any{map[string]any{ + "username": "alice", + "secret": "$6$stale$hash", + }}, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(pre-Set slow sync): %v", err) + } + + // First causal sync binds Running's crypt/cipher format with zero revert Sets. + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "user": []any{map[string]any{ + "username": "alice", + "secret": tc.targetVal, + }}, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(causal sync): %v", err) + } + + intentResp, err := f.ds.GetIntent(ctx, "intent1") + if err != nil { + t.Fatalf("GetIntent(intent1): %v", err) + } + intentUpds, err := intentResp.ToProtoUpdates(ctx) + if err != nil { + t.Fatalf("intentResp.ToProtoUpdates: %v", err) + } + if got := updatesByXPath(intentUpds)["/system/user[username=alice]/secret"]; got != cleartext { + t.Fatalf("GetIntent(intent1) secret = %q, want %q", got, cleartext) + } + + runningResp, err := f.ds.GetIntent(ctx, consts.RunningIntentName) + if err != nil { + t.Fatalf("GetIntent(running): %v", err) + } + runningUpds, err := runningResp.ToProtoUpdates(ctx) + if err != nil { + t.Fatalf("runningResp.ToProtoUpdates: %v", err) + } + if got := updatesByXPath(runningUpds)["/system/user[username=alice]/secret"]; got != tc.targetVal { + t.Fatalf("GetIntent(running) secret = %q, want %q", got, tc.targetVal) + } + + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + t.Fatalf("unexpected NOT_APPLIED deviation after crypt discovery: %v", ev) + } + } + + blame, err := f.ds.BlameConfig(ctx, false) + if err != nil { + t.Fatalf("BlameConfig: %v", err) + } + secretBlame := testhelper.FindBlameElement(blame, "system", "user", "alice", "secret") + if secretBlame == nil { + t.Fatalf("missing secret blame node in %v", blame) + } + if secretBlame.GetValue().GetStringVal() != cleartext || secretBlame.GetDeviationValue() != nil { + t.Fatalf("BlameConfig secret = (value=%v, deviation=%v), want (%q, nil)", + secretBlame.GetValue(), secretBlame.GetDeviationValue(), cleartext) + } + }) + } +} + +func TestDatastore_MutateOnWrite_LearnedKeylessSchemaPathPromotesSubsequentWritesToTargetedGet(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + const ( + aliceCleartext = "AliceSecret1" + aliceHash = "$6$rounds=5000$alicesalt$longhashedvalueexceeding32characterslimit" + bobCleartext = "BobSecret2" + bobHash = "$6$rounds=5000$bobsalt$longbobhashedvalueexceeding32characterslim" + replaceHash = "$6$rounds=5000$replsalt$longreplacehashedvalueexceeding32charlim" + ) + + // 1. First write on alice: unannotated plain string leaf -> Set only, no targeted Get. + f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + + aliceIntent := buildJSONIntent(t, f.ds, "alice-intent", 10, false, map[string]any{ + "system": map[string]any{ + "user": []any{map[string]any{ + "username": "alice", + "secret": aliceCleartext, + }}, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-alice", []*types.TransactionIntent{aliceIntent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-alice): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-alice"); err != nil { + t.Fatalf("TransactionConfirm(tx-alice): %v", err) + } + + // 2. First causal sync discovers crypt prefix on alice and learns /system/user/secret. + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "user": []any{map[string]any{ + "username": "alice", + "secret": aliceHash, + }}, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(alice causal sync): %v", err) + } + + // 3. Subsequent write on another instance (bob) of the learned keyless path + // issues targeted post-Set Get immediately and does not re-push converged alice. + bobSet := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + DoAndReturn(func(setCtx context.Context, source targettypes.TargetSource) (*sdcpb.SetDataResponse, error) { + upds, err := source.ToProtoUpdates(setCtx, true) + if err != nil { + return nil, err + } + pushed := updatesByXPath(upds) + if _, repushedAlice := pushed["/system/user[username=alice]/secret"]; repushedAlice { + t.Fatalf("converged alice secret was unexpectedly re-pushed: %v", pushed) + } + if got := pushed["/system/user[username=bob]/secret"]; got != bobCleartext { + t.Fatalf("pushed bob secret = %q, want %q", got, bobCleartext) + } + return &sdcpb.SetDataResponse{}, nil + }). + Times(1) + + f.sbi.EXPECT(). + Get(gomock.Any(), gomock.Any()). + After(bobSet). + DoAndReturn(func(_ context.Context, req *sdcpb.GetDataRequest) (*sdcpb.GetDataResponse, error) { + if len(req.GetPath()) != 1 || req.GetPath()[0].ToXPath(false) != "/system/user[username=bob]/secret" { + t.Fatalf("targeted Get paths = %v, want [/system/user[username=bob]/secret]", req.GetPath()) + } + return &sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{{ + Path: &sdcpb.Path{ + IsRootBased: true, + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("user", map[string]string{"username": "bob"}), + sdcpb.NewPathElem("secret", nil), + }, + }, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: bobHash}}, + }}, + }}, + }, nil + }). + Times(1) + + aliceRebundled := buildJSONIntent(t, f.ds, "alice-intent", 10, false, map[string]any{ + "system": map[string]any{ + "user": []any{map[string]any{ + "username": "alice", + "secret": aliceCleartext, + }}, + }, + }) + bobIntent := buildJSONIntent(t, f.ds, "bob-intent", 10, false, map[string]any{ + "system": map[string]any{ + "user": []any{map[string]any{ + "username": "bob", + "secret": bobCleartext, + }}, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-bob", []*types.TransactionIntent{aliceRebundled, bobIntent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-bob): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-bob"); err != nil { + t.Fatalf("TransactionConfirm(tx-bob): %v", err) + } + + runningResp, err := f.ds.GetIntent(ctx, consts.RunningIntentName) + if err != nil { + t.Fatalf("GetIntent(running): %v", err) + } + runningUpds, err := runningResp.ToProtoUpdates(ctx) + if err != nil { + t.Fatalf("runningResp.ToProtoUpdates: %v", err) + } + if got := updatesByXPath(runningUpds)["/system/user[username=bob]/secret"]; got != bobHash { + t.Fatalf("GetIntent(running) bob secret = %q, want immediate targeted readback %q", got, bobHash) + } + + // 4. Orphan-delete alice-intent while modifying hostname: Running retains alice's >32-char hash + // and validation skips Running on the learned mutate-on-write path just like schema-flagged leaves. + f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + + orphanAlice, err := f.ds.SdcpbTransactionIntentToInternalTI(ctx, &sdcpb.TransactionIntent{ + Intent: "alice-intent", + Priority: 10, + Delete: true, + Orphan: true, + }) + if err != nil { + t.Fatalf("SdcpbTransactionIntentToInternalTI(orphanAlice): %v", err) + } + hostIntent := buildJSONIntent(t, f.ds, "host-intent", 10, false, map[string]any{ + "system": map[string]any{"hostname": "router-1"}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-orphan-alice", []*types.TransactionIntent{orphanAlice, hostIntent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-orphan-alice): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-orphan-alice"); err != nil { + t.Fatalf("TransactionConfirm(tx-orphan-alice): %v", err) + } + + // 5. Full-config replace matching persisted intents preserves the learned path, + // issues targeted Get immediately, and binds the new baseline without a second Set. + replSet := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + replGet := f.sbi.EXPECT(). + Get(gomock.Any(), gomock.Any()). + After(replSet). + DoAndReturn(func(_ context.Context, req *sdcpb.GetDataRequest) (*sdcpb.GetDataResponse, error) { + if len(req.GetPath()) != 1 || req.GetPath()[0].ToXPath(false) != "/system/user[username=bob]/secret" { + t.Fatalf("replace targeted Get paths = %v, want [/system/user[username=bob]/secret]", req.GetPath()) + } + return &sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{{ + Path: &sdcpb.Path{ + IsRootBased: true, + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("user", map[string]string{"username": "bob"}), + sdcpb.NewPathElem("secret", nil), + }, + }, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: replaceHash}}, + }}, + }}, + }, nil + }). + Times(1) + expectEmptySet(t, f.sbi).After(replGet) + + replaceTI := buildJSONIntent(t, f.ds, consts.ReplaceIntentName, consts.ReplaceValuesPrio, false, map[string]any{ + "system": map[string]any{ + "hostname": "router-1", + "user": []any{map[string]any{ + "username": "bob", + "secret": bobCleartext, + }}, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-replace-learned", nil, replaceTI, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-replace-learned): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-replace-learned"); err != nil { + t.Fatalf("TransactionConfirm(tx-replace-learned): %v", err) + } +} + +func TestDatastore_MutateOnWrite_PreHashedIntentEnforcesByteForByteDrift(t *testing.T) { + const ( + preHashedA = "$6$saltA$hashA" + preHashedB = "$6$saltB$hashB" + ) + + t.Run("unannotated plain string pre-hashed intent reverts and does not learn path", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + txSet := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + + intent := buildJSONIntent(t, f.ds, "intent1", 10, false, map[string]any{ + "system": map[string]any{ + "user": []any{map[string]any{ + "username": "alice", + "secret": preHashedA, + }}, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-prehashed", []*types.TransactionIntent{intent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet: %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-prehashed"); err != nil { + t.Fatalf("TransactionConfirm: %v", err) + } + + // Differing hash in Running must trigger southbound revert pushing preHashedA. + revertSet := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + After(txSet). + DoAndReturn(func(setCtx context.Context, source targettypes.TargetSource) (*sdcpb.SetDataResponse, error) { + upds, err := source.ToProtoUpdates(setCtx, true) + if err != nil { + return nil, err + } + if got := updatesByXPath(upds)["/system/user[username=alice]/secret"]; got != preHashedA { + t.Fatalf("revert pushed secret = %q, want %q", got, preHashedA) + } + return &sdcpb.SetDataResponse{}, nil + }). + Times(1) + + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "user": []any{map[string]any{ + "username": "alice", + "secret": preHashedB, + }}, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(differing hash): %v", err) + } + + foundNotApplied := false + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && + ev.GetPath().ToXPath(false) == "/system/user[username=alice]/secret" { + foundNotApplied = true + } + } + if !foundNotApplied { + t.Fatal("expected NOT_APPLIED deviation when Running holds differing hash for pre-hashed intent") + } + + // Subsequent write must still not issue targeted Get because path was not learned. + f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + After(revertSet). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + + bobIntent := buildJSONIntent(t, f.ds, "bob-intent", 10, false, map[string]any{ + "system": map[string]any{ + "user": []any{map[string]any{ + "username": "bob", + "secret": "BobCleartext", + }}, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-bob-after-prehashed", []*types.TransactionIntent{bobIntent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-bob-after-prehashed): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-bob-after-prehashed"); err != nil { + t.Fatalf("TransactionConfirm(tx-bob-after-prehashed): %v", err) + } + }) + + t.Run("learned path pre-hashed intent rejects differing readback and sync hashes", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + // First learn /system/user/secret via cleartext alice. + f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + aliceIntent := buildJSONIntent(t, f.ds, "alice-intent", 10, false, map[string]any{ + "system": map[string]any{ + "user": []any{map[string]any{ + "username": "alice", + "secret": "AliceCleartext", + }}, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-learn-alice", []*types.TransactionIntent{aliceIntent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-learn-alice): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-learn-alice"); err != nil { + t.Fatalf("TransactionConfirm(tx-learn-alice): %v", err) + } + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "user": []any{map[string]any{ + "username": "alice", + "secret": "$6$alice$learned", + }}, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(learn alice): %v", err) + } + + // Now author a pre-hashed intent on bob (same learned keyless path /system/user/secret), + // where targeted Get fails and causal sync returns differing preHashedB. + bobSet := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + bobGet := f.sbi.EXPECT(). + Get(gomock.Any(), gomock.Any()). + After(bobSet). + Return(nil, errors.New("readback unavailable")). + Times(1) + + bobIntent := buildJSONIntent(t, f.ds, "bob-intent", 10, false, map[string]any{ + "system": map[string]any{ + "user": []any{map[string]any{ + "username": "bob", + "secret": preHashedA, + }}, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-prehashed-bob", []*types.TransactionIntent{bobIntent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-prehashed-bob): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-prehashed-bob"); err != nil { + t.Fatalf("TransactionConfirm(tx-prehashed-bob): %v", err) + } + + // Causal sync with differing preHashedB must revert bob to preHashedA (and targeted Get on revert). + revSet := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + After(bobGet). + DoAndReturn(func(setCtx context.Context, source targettypes.TargetSource) (*sdcpb.SetDataResponse, error) { + upds, err := source.ToProtoUpdates(setCtx, true) + if err != nil { + return nil, err + } + if got := updatesByXPath(upds)["/system/user[username=bob]/secret"]; got != preHashedA { + t.Fatalf("revert pushed bob secret = %q, want %q", got, preHashedA) + } + return &sdcpb.SetDataResponse{}, nil + }). + Times(1) + f.sbi.EXPECT(). + Get(gomock.Any(), gomock.Any()). + After(revSet). + Return(&sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{{ + Path: &sdcpb.Path{ + IsRootBased: true, + Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("user", map[string]string{"username": "bob"}), + sdcpb.NewPathElem("secret", nil), + }, + }, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: preHashedB}}, + }}, + }}, + }, nil). + Times(1) + + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "user": []any{ + map[string]any{"username": "alice", "secret": "$6$alice$learned"}, + map[string]any{"username": "bob", "secret": preHashedB}, + }, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(bob differing hash): %v", err) + } + + // Even when targeted Get returned preHashedB on the revert, preHashedB must NOT be + // bound as a confirmed baseline for preHashedA — NOT_APPLIED must still be raised. + foundBobNotApplied := false + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && + ev.GetPath().ToXPath(false) == "/system/user[username=bob]/secret" { + foundBobNotApplied = true + } + } + if !foundBobNotApplied { + t.Fatal("expected NOT_APPLIED when targeted Get returned differing hash for pre-hashed intent") + } + }) +} + +func TestDatastore_MutateOnWrite_UnannotatedNonCryptDriftRevertsWithoutLearning(t *testing.T) { + for _, driftedVal := range []string{ + "drifted-plain", + "$0$cleartext", + "$3$nthash", + "$4$unknown", + "$argon2d$v=19$m=4096$salt$hash", + "$6$", + "$pbkdf2$", + "two tokens hash", + " hash", + "hash2", + } { + t.Run("revertive rejects_"+driftedVal, func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + const authored = "router-1" + + txSet := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + + intent := buildJSONIntent(t, f.ds, "intent1", 10, false, map[string]any{ + "system": map[string]any{"hostname": authored}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-host", []*types.TransactionIntent{intent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet: %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-host"); err != nil { + t.Fatalf("TransactionConfirm: %v", err) + } + + revertSet := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + After(txSet). + DoAndReturn(func(setCtx context.Context, source targettypes.TargetSource) (*sdcpb.SetDataResponse, error) { + upds, err := source.ToProtoUpdates(setCtx, true) + if err != nil { + return nil, err + } + if got := updatesByXPath(upds)["/system/hostname"]; got != authored { + t.Fatalf("revert pushed hostname = %q, want %q", got, authored) + } + return &sdcpb.SetDataResponse{}, nil + }). + Times(1) + + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hostname": driftedVal}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(non-crypt drift %q): %v", driftedVal, err) + } + + foundNotApplied := false + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && + ev.GetPath().ToXPath(false) == "/system/hostname" { + foundNotApplied = true + } + } + if !foundNotApplied { + t.Fatalf("expected NOT_APPLIED for non-crypt drift %q", driftedVal) + } + + // Path was not learned, so a subsequent TransactionSet still issues zero targeted Gets. + f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + After(revertSet). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + + intentV2 := buildJSONIntent(t, f.ds, "intent1", 10, false, map[string]any{ + "system": map[string]any{"hostname": "router-2"}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-host-v2", []*types.TransactionIntent{intentV2}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(v2): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-host-v2"); err != nil { + t.Fatalf("TransactionConfirm(v2): %v", err) + } + }) + } + + t.Run("first causal sync clears pending marker so later crypt-shaped CLI drift still reverts", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + const authored = "router-clean" + + txSet := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + + intent := buildJSONIntent(t, f.ds, "intent1", 10, false, map[string]any{ + "system": map[string]any{"hostname": authored}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-clean", []*types.TransactionIntent{intent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet: %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-clean"); err != nil { + t.Fatalf("TransactionConfirm: %v", err) + } + + // First causal sync echoes authored value -> clears pendingCaptureAt without learning. + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hostname": authored}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(clean first sync): %v", err) + } + + // Later CLI edit to a crypt-shaped value must NOT be accepted as a Set mutation. + f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + After(txSet). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hostname": "$6$cli-injected$hash"}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(later CLI drift): %v", err) + } + }) + + t.Run("incremental sync with nil deletes clears unchanged pending marker and discovers crypt secrets", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + const ( + authoredHost = "stream-router" + authoredSecret = "StreamSecret1" + hashedSecret = "$6$stream$hashedsecretvalue" + ) + + txSet := f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + Return(&sdcpb.SetDataResponse{}, nil). + Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + + intent := buildJSONIntent(t, f.ds, "intent1", 10, false, map[string]any{ + "system": map[string]any{ + "hostname": authoredHost, + "user": []any{map[string]any{ + "username": "alice", + "secret": authoredSecret, + }}, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-stream", []*types.TransactionIntent{intent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet: %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-stream"); err != nil { + t.Fatalf("TransactionConfirm: %v", err) + } + + // Incremental sync (deletes == nil) on an unrelated leaf must NOT clear alice's pending marker. + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), nil, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "user": []any{map[string]any{ + "username": "other", + }}, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(unrelated stream update): %v", err) + } + + // First causal incremental sync covering hostname (unchanged) and alice secret (hashed) + // with deletes == nil must bind alice's hash AND clear hostname's pending marker. + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), nil, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "hostname": authoredHost, + "user": []any{map[string]any{ + "username": "alice", + "secret": hashedSecret, + }}, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(causal stream update): %v", err) + } + + // Later out-of-band CLI edit of hostname to a crypt-shaped value via incremental sync + // must revert to authoredHost rather than being auto-accepted or learned. + f.sbi.EXPECT(). + Set(gomock.Any(), gomock.Any()). + After(txSet). + DoAndReturn(func(setCtx context.Context, source targettypes.TargetSource) (*sdcpb.SetDataResponse, error) { + upds, err := source.ToProtoUpdates(setCtx, true) + if err != nil { + return nil, err + } + if got := updatesByXPath(upds)["/system/hostname"]; got != authoredHost { + t.Fatalf("revert pushed hostname = %q, want %q", got, authoredHost) + } + return &sdcpb.SetDataResponse{}, nil + }). + Times(1) + + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), nil, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hostname": "$6$later-stream-cli$hash"}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(later stream CLI drift): %v", err) + } + }) + + t.Run("unrelated nil-importer delete and keyless list sync paths handle pending markers accurately", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + // Seed initial state then rotate alice's unannotated secret so Running has IsUpdated=true. + f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(2) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + + seed := buildJSONIntent(t, f.ds, "intent1", 10, true, map[string]any{ + "system": map[string]any{ + "hostname": "old-host", + "user": []any{map[string]any{ + "username": "alice", + "secret": "SecretV1", + }}, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-seed", []*types.TransactionIntent{seed}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(seed): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-seed"); err != nil { + t.Fatalf("TransactionConfirm(seed): %v", err) + } + + rotated := buildJSONIntent(t, f.ds, "intent1", 10, true, map[string]any{ + "system": map[string]any{ + "hostname": "old-host", + "user": []any{map[string]any{ + "username": "alice", + "secret": "SecretV2", + }}, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-rotate", []*types.TransactionIntent{rotated}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(rotate): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-rotate"); err != nil { + t.Fatalf("TransactionConfirm(rotate): %v", err) + } + + // Unrelated nil-importer delete on /system/hostname must NOT evict alice's pending marker. + unrelatedDel := []*sdcpb.Path{{ + IsRootBased: true, + Elem: []*sdcpb.PathElem{sdcpb.NewPathElem("system", nil), sdcpb.NewPathElem("hostname", nil)}, + }} + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), unrelatedDel, nil); err != nil { + t.Fatalf("ApplyToRunning(unrelated nil importer): %v", err) + } + + // Syncing keyless list path /system/user covers alice and discovers the crypt secret cleanly. + keylessUserList := []*sdcpb.Path{{ + IsRootBased: true, + Elem: []*sdcpb.PathElem{sdcpb.NewPathElem("system", nil), sdcpb.NewPathElem("user", nil)}, + }} + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), keylessUserList, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "hostname": "old-host", + "user": []any{map[string]any{ + "username": "alice", + "secret": "$6$rotated$hashV2", + }}, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(keyless list sync): %v", err) + } + + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + t.Fatalf("unexpected NOT_APPLIED after keyless list crypt discovery: %v", ev) + } + } + }) +} diff --git a/pkg/datastore/post_set_readback.go b/pkg/datastore/post_set_readback.go index 0daea1f1..3a03a9fa 100644 --- a/pkg/datastore/post_set_readback.go +++ b/pkg/datastore/post_set_readback.go @@ -33,15 +33,32 @@ func (d *Datastore) isNoopTarget() bool { return d.config != nil && d.config.SBI != nil && strings.EqualFold(d.config.SBI.Type, "noop") } -func isMutateOnWriteLeafEntry(le *api.LeafEntry) bool { - return le != nil && le.GetEntry() != nil && le.GetEntry().GetSchema().IsMutateOnWrite() +func (d *Datastore) isMutateOnWriteLeafEntry(le *api.LeafEntry) bool { + if le == nil || le.GetEntry() == nil { + return false + } + if api.IsMutateOnWriteEntry(le.GetEntry()) { + return true + } + return d != nil && d.confirmedApplied.IsLearnedMutateOnWritePath(le.SdcpbPath()) } -func collectPushedMutateOnWritePaths(updates api.LeafVariantSlice) []*sdcpb.Path { +func isPlainStringLeafEntry(le *api.LeafEntry) bool { + if le == nil || le.GetEntry() == nil { + return false + } + if le.GetEntry().GetSchema().GetField().GetType().GetType() != "string" { + return false + } + _, ok := le.Value().GetValue().(*sdcpb.TypedValue_StringVal) + return ok +} + +func (d *Datastore) collectPushedMutateOnWritePaths(updates api.LeafVariantSlice) []*sdcpb.Path { var paths []*sdcpb.Path seen := make(map[canonicalLeafPath]struct{}) for _, le := range updates { - if !isMutateOnWriteLeafEntry(le) || le.GetDeleteFlag() || le.GetExplicitDeleteFlag() { + if !d.isMutateOnWriteLeafEntry(le) || le.GetDeleteFlag() || le.GetExplicitDeleteFlag() { continue } p := le.SdcpbPath() @@ -120,44 +137,83 @@ func (d *Datastore) gnmiReadbackEncoding() (sdcpb.Encoding, bool) { return enc, true } -// applyReadbacksAndWriteBackRunning binds non-empty post-Set readbacks and -// leaves missing values pending for causal sync capture while updating Running. func (d *Datastore) applyReadbacksAndWriteBackRunning(ctx context.Context, updates api.LeafVariantSlice, deletes treetypes.DeleteEntriesList, readbacks map[canonicalLeafPath]*sdcpb.TypedValue, setDoneUnixNano int64) error { - return d.writeReadbacksToRunning(ctx, updates, deletes, readbacks, func(le *api.LeafEntry, rb *sdcpb.TypedValue, ok bool) { - if ok { - d.confirmedApplied.RecordAfter(le.SdcpbPath(), le.Owner(), le.Value(), rb, setDoneUnixNano) - } else { - d.confirmedApplied.MarkPending(le.SdcpbPath(), le.Owner(), le.Value(), setDoneUnixNano) - } - }) + d.evictDeletedSubtrees(deletes) + return d.writeReadbacksToRunning( + ctx, + updates, + deletes, + readbacks, + func(le *api.LeafEntry) (string, bool) { return le.Owner(), true }, + setDoneUnixNano, + ) } -// reconcileReplaceReadbacksAndWriteBackRunning clears prior baselines after a -// full-config replace, binds non-empty readbacks to matching winning persisted -// owners when present, and writes confirmed applied values into Running. +// reconcileReplaceReadbacksAndWriteBackRunning clears prior value baselines +// while preserving learned mutate-on-write schema paths, records readbacks or +// plain-string discovery markers for leaves matching winning persisted owners, +// and updates Running. func (d *Datastore) reconcileReplaceReadbacksAndWriteBackRunning(ctx context.Context, updates api.LeafVariantSlice, deletes treetypes.DeleteEntriesList, readbacks map[canonicalLeafPath]*sdcpb.TypedValue, setDoneUnixNano int64) error { d.confirmedApplied.ClearAll() var persistedIntents *tree.RootEntry - if len(collectPushedMutateOnWritePaths(updates)) > 0 { - if root, err := d.NewEmptyTree(ctx); err == nil { - if _, loadErr := d.LoadAllButRunningIntents(ctx, root); loadErr == nil && root.FinishInsertionPhase(ctx) == nil { - persistedIntents = root - } + if root, err := d.NewEmptyTree(ctx); err == nil { + if _, loadErr := d.LoadAllButRunningIntents(ctx, root); loadErr == nil && root.FinishInsertionPhase(ctx) == nil { + persistedIntents = root } } - return d.writeReadbacksToRunning(ctx, updates, deletes, readbacks, func(le *api.LeafEntry, rb *sdcpb.TypedValue, ok bool) { - owner, matched := winningPersistedOwnerWithValue(ctx, persistedIntents, le.SdcpbPath(), le.Value()) - if !matched { - return + return d.writeReadbacksToRunning( + ctx, + updates, + deletes, + readbacks, + func(le *api.LeafEntry) (string, bool) { + return winningPersistedOwnerWithValue(ctx, persistedIntents, le.SdcpbPath(), le.Value()) + }, + setDoneUnixNano, + ) +} + +func (d *Datastore) evictDeletedSubtrees(deletes treetypes.DeleteEntriesList) { + for _, del := range deletes { + d.confirmedApplied.DeleteSubtree(del.SdcpbPath()) + } +} + +func (d *Datastore) recordMutateOnWriteOutcome(path *sdcpb.Path, owner string, intendedVal, rb *sdcpb.TypedValue, hasReadback bool, setDoneUnixNano int64) { + if hasReadback { + d.confirmedApplied.RecordAfter(path, owner, intendedVal, rb, setDoneUnixNano) + return + } + d.confirmedApplied.MarkPending(path, owner, intendedVal, setDoneUnixNano) +} + +// reconcilePlainStringPush updates discovery state for an unannotated plain +// string push: reserved running/default owners are ignored, values matching the +// crypt/cipher allowlist evict any prior baseline for path, and non-hashed +// values record a pending discovery candidate. +func (d *Datastore) reconcilePlainStringPush(path *sdcpb.Path, owner string, val *sdcpb.TypedValue, setDoneUnixNano int64) { + if owner == "" || owner == consts.RunningIntentName || owner == consts.DefaultsIntentName { + return + } + if matchesCryptOrCipherValue(val) { + d.confirmedApplied.Delete(path) + return + } + d.confirmedApplied.MarkDiscoveryCandidate(path, owner, val, setDoneUnixNano) +} + +func (d *Datastore) reconcilePlainStringRevertPushes(updates api.LeafVariantSlice, deletes treetypes.DeleteEntriesList, setDoneUnixNano int64) { + d.evictDeletedSubtrees(deletes) + for _, le := range updates { + if le.GetDeleteFlag() || le.GetExplicitDeleteFlag() { + continue } - if ok { - d.confirmedApplied.RecordAfter(le.SdcpbPath(), owner, le.Value(), rb, setDoneUnixNano) - } else { - d.confirmedApplied.MarkPending(le.SdcpbPath(), owner, le.Value(), setDoneUnixNano) + if !d.isMutateOnWriteLeafEntry(le) && isPlainStringLeafEntry(le) { + d.reconcilePlainStringPush(le.SdcpbPath(), le.Owner(), le.Value(), setDoneUnixNano) } - }) + } } func (d *Datastore) writeReadbacksToRunning( @@ -165,17 +221,24 @@ func (d *Datastore) writeReadbacksToRunning( updates api.LeafVariantSlice, deletes treetypes.DeleteEntriesList, readbacks map[canonicalLeafPath]*sdcpb.TypedValue, - onMutateOnWrite func(le *api.LeafEntry, rb *sdcpb.TypedValue, hasReadback bool), + resolveOwner func(le *api.LeafEntry) (string, bool), + setDoneUnixNano int64, ) error { runningUpdates := make([]*treetypes.PathAndUpdate, 0, len(updates)) for _, le := range updates { runVal := le.Value() - if isMutateOnWriteLeafEntry(le) { + if d.isMutateOnWriteLeafEntry(le) { rb, ok := readbacks[newCanonicalLeafPath(le.SdcpbPath())] - onMutateOnWrite(le, rb, ok) + if owner, matched := resolveOwner(le); matched { + d.recordMutateOnWriteOutcome(le.SdcpbPath(), owner, le.Value(), rb, ok, setDoneUnixNano) + } if ok { runVal = proto.Clone(rb).(*sdcpb.TypedValue) } + } else if !le.GetDeleteFlag() && !le.GetExplicitDeleteFlag() && isPlainStringLeafEntry(le) { + if owner, matched := resolveOwner(le); matched { + d.reconcilePlainStringPush(le.SdcpbPath(), owner, le.Value(), setDoneUnixNano) + } } runningUpdates = append(runningUpdates, treetypes.NewPathAndUpdate( le.SdcpbPath(), diff --git a/pkg/datastore/sync.go b/pkg/datastore/sync.go index 71ecabed..c5b7b3b4 100644 --- a/pkg/datastore/sync.go +++ b/pkg/datastore/sync.go @@ -7,6 +7,7 @@ import ( "time" "github.com/sdcio/data-server/pkg/tree" + "github.com/sdcio/data-server/pkg/tree/api" "github.com/sdcio/data-server/pkg/tree/api/adapter" "github.com/sdcio/data-server/pkg/tree/consts" "github.com/sdcio/data-server/pkg/tree/importer" @@ -16,7 +17,6 @@ import ( "github.com/sdcio/data-server/pkg/utils" "github.com/sdcio/logger" sdcpb "github.com/sdcio/sdc-protos/sdcpb" - "google.golang.org/protobuf/proto" ) // ApplyToRunning commits one sync observation. syncStartedAt is Unix @@ -57,10 +57,13 @@ func (d *Datastore) ApplyToRunning(ctx context.Context, syncStartedAt int64, del } // import new config if provided + var importedPaths map[canonicalLeafPath]bool if importer != nil { - _, err := d.syncTree.ImportConfig(ctx, &sdcpb.Path{}, importer, treetypes.NewUpdateInsertFlags(), d.taskPool) - if err != nil { - return err + probes := d.beginPendingImportProbes(ctx, syncStartedAt, deletes) + _, importErr := d.syncTree.ImportConfig(ctx, &sdcpb.Path{}, importer, treetypes.NewUpdateInsertFlags(), d.taskPool) + importedPaths = d.finishPendingImportProbes(ctx, probes) + if importErr != nil { + return importErr } } @@ -88,7 +91,7 @@ func (d *Datastore) ApplyToRunning(ctx context.Context, syncStartedAt int64, del } } - if err := d.reconcilePendingCaptures(ctx, syncStartedAt, deletes); err != nil { + if err := d.reconcilePendingCaptures(ctx, syncStartedAt, deletes, importedPaths); err != nil { return err } @@ -128,7 +131,69 @@ func (d *Datastore) ApplyToRunning(ctx context.Context, syncStartedAt int64, del } -func (d *Datastore) reconcilePendingCaptures(ctx context.Context, syncStartedAt int64, syncPaths []*sdcpb.Path) error { +// pendingImportProbe tracks temporary Running state across a single ImportConfig +// call so ApplyToRunning can tell whether an incremental importer touched a +// causal pending path. Callers of beginPendingImportProbes must always invoke +// finishPendingImportProbes before RemoveDeletedProcessor runs, even on import error. +type pendingImportProbe struct { + key canonicalLeafPath + path *sdcpb.Path + running *api.LeafEntry +} + +// beginPendingImportProbes prepares observation probes on d.syncTree for causal +// pending paths not already covered by syncPaths; callers must hold syncTreeMutex. +func (d *Datastore) beginPendingImportProbes(ctx context.Context, syncStartedAt int64, syncPaths []*sdcpb.Path) []pendingImportProbe { + var probes []pendingImportProbe + for _, pending := range d.confirmedApplied.CausalCaptures() { + if !pending.IsPending() || syncStartedAt < pending.captureAfterNano || pathCoveredBySync(pending.path, syncPaths) { + continue + } + var running *api.LeafEntry + entry, err := ops.NavigateSdcpbPath(ctx, d.syncTree.Entry, pending.path) + if err == nil && entry != nil { + if r := entry.GetLeafVariants().GetByOwner(consts.RunningIntentName); r != nil { + if r.GetDeleteFlag() { + continue + } + r.MarkDelete(false) + running = r + } + } + probes = append(probes, pendingImportProbe{ + key: newCanonicalLeafPath(pending.path), + path: pending.path, + running: running, + }) + } + return probes +} + +// finishPendingImportProbes restores temporary probe markers on untouched Running +// leaves and returns the canonical paths observed during ImportConfig. +func (d *Datastore) finishPendingImportProbes(ctx context.Context, probes []pendingImportProbe) map[canonicalLeafPath]bool { + if len(probes) == 0 { + return nil + } + observed := make(map[canonicalLeafPath]bool, len(probes)) + for _, probe := range probes { + if probe.running != nil { + if !probe.running.GetDeleteFlag() { + observed[probe.key] = true + } else { + probe.running.DropDeleteFlag() + } + continue + } + entry, err := ops.NavigateSdcpbPath(ctx, d.syncTree.Entry, probe.path) + if err == nil && entry != nil && entry.GetLeafVariants().GetByOwner(consts.RunningIntentName) != nil { + observed[probe.key] = true + } + } + return observed +} + +func (d *Datastore) reconcilePendingCaptures(ctx context.Context, syncStartedAt int64, syncPaths []*sdcpb.Path, importedPaths map[canonicalLeafPath]bool) error { for _, pending := range d.confirmedApplied.CausalCaptures() { if syncStartedAt < pending.captureAfterNano { restoreValue := pending.intendedValue @@ -145,24 +210,23 @@ func (d *Datastore) reconcilePendingCaptures(ctx context.Context, syncStartedAt } continue } - if !pending.pending { + if !pending.IsPending() { continue } + wasObserved := pathCoveredBySync(pending.path, syncPaths) || importedPaths[newCanonicalLeafPath(pending.path)] + if !wasObserved { + continue + } var observed *sdcpb.TypedValue - wasObserved := pathCoveredBySync(pending.path, syncPaths) entry, err := ops.NavigateSdcpbPath(ctx, d.syncTree.Entry, pending.path) if err == nil && entry != nil { if running := entry.GetLeafVariants().GetByOwner(consts.RunningIntentName); running != nil { observed = running.Value() - wasObserved = wasObserved || running.GetNewFlag() || running.GetUpdateFlag() } } else if err != nil && !errors.Is(err, ops.ErrNavigateSdcpbPathNotFound) { return err } - if !wasObserved { - continue - } d.confirmedApplied.CompletePending(pending, observed) } return nil @@ -171,18 +235,7 @@ func (d *Datastore) reconcilePendingCaptures(ctx context.Context, syncStartedAt func pathCoveredBySync(path *sdcpb.Path, syncPaths []*sdcpb.Path) bool { path = canonicalPath(path) for _, syncPath := range syncPaths { - syncPath = canonicalPath(syncPath) - if len(syncPath.GetElem()) > len(path.GetElem()) { - continue - } - covered := true - for i, elem := range syncPath.GetElem() { - if !proto.Equal(elem, path.GetElem()[i]) { - covered = false - break - } - } - if covered { + if canonicalPath(syncPath).IsParentPathOf(path) { return true } } @@ -243,12 +296,14 @@ func (d *Datastore) performRevert(ctx context.Context, t *tree.RootEntry) error return nil } setDoneUnixNano := time.Now().UnixNano() - mutateOnWritePaths := collectPushedMutateOnWritePaths(updates) + mutateOnWritePaths := d.collectPushedMutateOnWritePaths(updates) if len(mutateOnWritePaths) > 0 { readbacks := d.fetchMutateOnWriteReadbacks(ctx, mutateOnWritePaths) if err := d.applyReadbacksAndWriteBackRunning(ctx, updates, del, readbacks, setDoneUnixNano); err != nil { return err } + } else { + d.reconcilePlainStringRevertPushes(updates, del, setDoneUnixNano) } } diff --git a/pkg/datastore/transaction_rpc.go b/pkg/datastore/transaction_rpc.go index 9a343a28..99e89b7b 100644 --- a/pkg/datastore/transaction_rpc.go +++ b/pkg/datastore/transaction_rpc.go @@ -153,7 +153,7 @@ func (d *Datastore) replaceIntent(ctx context.Context, transaction *types.Transa // retrieve the data that is meant to be send southbound (towards the device) updates := root.GetHighestPrecedence(true) deletes := treetypes.DeleteEntriesList{root} - readbacks := d.fetchMutateOnWriteReadbacks(ctx, collectPushedMutateOnWritePaths(updates)) + readbacks := d.fetchMutateOnWriteReadbacks(ctx, d.collectPushedMutateOnWritePaths(updates)) err = d.reconcileReplaceReadbacksAndWriteBackRunning(ctx, updates, deletes, readbacks, setDoneUnixNano) if err != nil { @@ -338,7 +338,7 @@ func (d *Datastore) lowlevelTransactionSet(ctx context.Context, transaction *typ } setDoneUnixNano := time.Now().UnixNano() result.Warnings = append(result.Warnings, dataResp.GetWarnings()...) - readbacks := d.fetchMutateOnWriteReadbacks(ctx, collectPushedMutateOnWritePaths(updates)) + readbacks := d.fetchMutateOnWriteReadbacks(ctx, d.collectPushedMutateOnWritePaths(updates)) log.Info("transaction applied") diff --git a/pkg/tree/api/tree_context.go b/pkg/tree/api/tree_context.go index 5fc43391..c36776b7 100644 --- a/pkg/tree/api/tree_context.go +++ b/pkg/tree/api/tree_context.go @@ -13,6 +13,12 @@ type ConfirmedAppliedValueResolver interface { Lookup(path *sdcpb.Path, owner string, intendedValue *sdcpb.TypedValue) *sdcpb.TypedValue } +// LearnedMutateOnWritePathSet reports whether a leaf's keyless schema path has +// been dynamically learned as mutate-on-write for the target. +type LearnedMutateOnWritePathSet interface { + IsLearnedMutateOnWritePath(path *sdcpb.Path) bool +} + type TreeContext interface { PoolFactory() pool.VirtualPoolFactory SchemaClient() schemaClient.SchemaClientBound @@ -21,4 +27,21 @@ type TreeContext interface { NonRevertiveInfo() NonRevertiveInfos // ConfirmedAppliedValue returns the confirmed applied value matching path, owner, and intendedValue, or nil when none matches. ConfirmedAppliedValue(path *sdcpb.Path, owner string, intendedValue *sdcpb.TypedValue) *sdcpb.TypedValue + // IsLearnedMutateOnWritePath reports whether path's keyless schema path was dynamically learned as mutate-on-write. + IsLearnedMutateOnWritePath(path *sdcpb.Path) bool +} + +// IsMutateOnWriteEntry reports whether e is classified as a mutate-on-write +// leaf by its YANG schema or by its tree context's learned path set. +func IsMutateOnWriteEntry(e Entry) bool { + if e == nil { + return false + } + if e.GetSchema().IsMutateOnWrite() { + return true + } + if tc := e.GetTreeContext(); tc != nil { + return tc.IsLearnedMutateOnWritePath(e.SdcpbPath()) + } + return false } diff --git a/pkg/tree/ops/validation/validation_dispatch.go b/pkg/tree/ops/validation/validation_dispatch.go index b83d0967..38bfe754 100644 --- a/pkg/tree/ops/validation/validation_dispatch.go +++ b/pkg/tree/ops/validation/validation_dispatch.go @@ -11,7 +11,7 @@ import ( func validatedLeafVariant(e api.Entry) *api.LeafEntry { lv := e.GetLeafVariants().GetHighestPrecedence(false, true, false) - if lv != nil && lv.Owner() == consts.RunningIntentName && e.GetSchema().IsMutateOnWrite() { + if lv != nil && lv.Owner() == consts.RunningIntentName && api.IsMutateOnWriteEntry(e) { return nil } return lv diff --git a/pkg/tree/tree_context.go b/pkg/tree/tree_context.go index 3deaac80..aa00a9fb 100644 --- a/pkg/tree/tree_context.go +++ b/pkg/tree/tree_context.go @@ -10,19 +10,26 @@ import ( // TreeContextOption configures optional collaborators on a TreeContext. type TreeContextOption func(*TreeContext) -// WithConfirmedAppliedValues wires a read-only baseline resolver for mutate-on-write leaves. +// WithConfirmedAppliedValues wires a read-only baseline resolver for +// mutate-on-write leaves. When resolver also implements +// api.LearnedMutateOnWritePathSet, TreeContext queries it for dynamically +// learned mutate-on-write schema paths. func WithConfirmedAppliedValues(resolver api.ConfirmedAppliedValueResolver) TreeContextOption { return func(tc *TreeContext) { tc.confirmedAppliedValues = resolver + if learned, ok := resolver.(api.LearnedMutateOnWritePathSet); ok { + tc.learnedMutateOnWritePaths = learned + } } } type TreeContext struct { - schemaClient schemaClient.SchemaClientBound - nonRevertiveInfo api.NonRevertiveInfos - explicitDeletes *api.DeletePathSet - poolFactory pool.VirtualPoolFactory - confirmedAppliedValues api.ConfirmedAppliedValueResolver + schemaClient schemaClient.SchemaClientBound + nonRevertiveInfo api.NonRevertiveInfos + explicitDeletes *api.DeletePathSet + poolFactory pool.VirtualPoolFactory + confirmedAppliedValues api.ConfirmedAppliedValueResolver + learnedMutateOnWritePaths api.LearnedMutateOnWritePathSet } func NewTreeContext(sc schemaClient.SchemaClientBound, poolFactory pool.VirtualPoolFactory, opts ...TreeContextOption) *TreeContext { @@ -43,9 +50,10 @@ func NewTreeContext(sc schemaClient.SchemaClientBound, poolFactory pool.VirtualP // deepCopy root is required to be set manually func (t *TreeContext) DeepCopy() api.TreeContext { tc := &TreeContext{ - schemaClient: t.schemaClient, - poolFactory: t.poolFactory, - confirmedAppliedValues: t.confirmedAppliedValues, + schemaClient: t.schemaClient, + poolFactory: t.poolFactory, + confirmedAppliedValues: t.confirmedAppliedValues, + learnedMutateOnWritePaths: t.learnedMutateOnWritePaths, } tc.nonRevertiveInfo = t.nonRevertiveInfo.DeepCopy() @@ -75,3 +83,10 @@ func (t *TreeContext) ConfirmedAppliedValue(path *sdcpb.Path, owner string, inte } return t.confirmedAppliedValues.Lookup(path, owner, intendedValue) } + +func (t *TreeContext) IsLearnedMutateOnWritePath(path *sdcpb.Path) bool { + if t == nil || t.learnedMutateOnWritePaths == nil { + return false + } + return t.learnedMutateOnWritePaths.IsLearnedMutateOnWritePath(path) +} From a3fbbad42716623989de7207d6b359917d9e3206 Mon Sep 17 00:00:00 2001 From: Markus Vahlenkamp Date: Mon, 23 Nov 2026 14:42:32 +0100 Subject: [PATCH 6/7] feat(datastore,tree): seed non-revertive mutate-on-write baselines on cold start and recovery Signed-off-by: Markus Vahlenkamp --- pkg/datastore/baseline_seeding.go | 387 +++++ pkg/datastore/confirmed_applied_values.go | 313 +++- pkg/datastore/datastore_rpc.go | 13 +- pkg/datastore/mutate_on_write_test.go | 1491 +++++++++++++++++++- pkg/datastore/sync.go | 109 +- pkg/datastore/target/gnmi/get.go | 7 + pkg/datastore/target/gnmi/stream.go | 33 +- pkg/datastore/target/gnmi/stream_test.go | 71 +- pkg/datastore/target/types/runningstore.go | 7 + pkg/datastore/transaction_rpc.go | 23 + pkg/tree/api/leaf_variants.go | 23 + pkg/tree/api/tree_context.go | 2 + pkg/tree/ops/navigatesdcpbpath.go | 27 + pkg/tree/tree_context.go | 6 + 14 files changed, 2371 insertions(+), 141 deletions(-) create mode 100644 pkg/datastore/baseline_seeding.go diff --git a/pkg/datastore/baseline_seeding.go b/pkg/datastore/baseline_seeding.go new file mode 100644 index 00000000..f349b5e9 --- /dev/null +++ b/pkg/datastore/baseline_seeding.go @@ -0,0 +1,387 @@ +// Copyright 2024 Nokia +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package datastore + +import ( + "context" + + "github.com/sdcio/data-server/pkg/datastore/types" + "github.com/sdcio/data-server/pkg/tree" + "github.com/sdcio/data-server/pkg/tree/api" + "github.com/sdcio/data-server/pkg/tree/consts" + "github.com/sdcio/data-server/pkg/tree/ops" + treetypes "github.com/sdcio/data-server/pkg/tree/types" + sdcpb "github.com/sdcio/sdc-protos/sdcpb" +) + +// learnedPathOverlay combines permanently learned mutate-on-write paths with +// validation-scoped paths discovered on a single transaction's tree. +type learnedPathOverlay struct { + base api.LearnedMutateOnWritePathSet + transient map[keylessLeafPath]struct{} +} + +func (o learnedPathOverlay) IsLearnedMutateOnWritePath(path *sdcpb.Path) bool { + if o.base != nil && o.base.IsLearnedMutateOnWritePath(path) { + return true + } + _, ok := o.transient[newKeylessLeafPath(path)] + return ok +} + +// ensureColdStartCandidatesLoaded registers pre-existing Non-revertive intents +// from cacheClient as awaiting initial-sync baseline seeding once per Datastore +// lifetime, before the first sync or write transaction modifies cache state. +// Callers must not hold syncTreeMutex. +func (d *Datastore) ensureColdStartCandidatesLoaded(ctx context.Context) error { + if d == nil || d.confirmedApplied == nil || d.cacheClient == nil || d.schemaClient == nil { + return nil + } + d.coldStartMu.Lock() + defer d.coldStartMu.Unlock() + if d.coldStartLoaded { + return nil + } + + intentTree, err := d.NewEmptyTree(ctx) + if err != nil { + return err + } + intentNames, err := d.LoadAllButRunningIntents(ctx, intentTree) + if err != nil { + return err + } + if len(intentNames) == 0 { + d.coldStartLoaded = true + return nil + } + hasNonRevertive := false + for _, name := range intentNames { + if intentTree.GetTreeContext().NonRevertiveInfo().IsGenerallyNonRevertive(name) { + hasNonRevertive = true + break + } + } + if !hasNonRevertive { + d.coldStartLoaded = true + return nil + } + if err := intentTree.FinishInsertionPhase(ctx); err != nil { + return err + } + + walkActiveIntendedWinners(intentTree.Entry, func(entry api.Entry, winning *api.LeafEntry) { + if !intentTree.GetTreeContext().NonRevertiveInfo().IsNonRevertive(winning.Owner(), entry) { + return + } + d.armInitialSyncSeed(winning, true) + }) + d.coldStartLoaded = true + return nil +} + +// attachValidationCryptOverlay installs a validation-scoped learned-path overlay +// onto root's TreeContext for unannotated crypt leaves won by PreviouslyApplied +// Non-revertive intents and returns a restore callback that detaches it once +// validation finishes. +func (d *Datastore) attachValidationCryptOverlay(root *tree.RootEntry, newIntents map[string]*types.TransactionIntent) func() { + noop := func() {} + if d == nil || root == nil || root.GetTreeContext() == nil { + return noop + } + eligibleOwners := eligiblePreviouslyAppliedOwners(newIntents) + if len(eligibleOwners) == 0 { + return noop + } + + transient := make(map[keylessLeafPath]struct{}) + walkEligibleNonRevertiveWinners(root, eligibleOwners, func(entry api.Entry, winning *api.LeafEntry) { + mode, ok := baselineSeedingMode(winning) + if !ok || mode != modeCryptDiscovery { + return + } + running := entry.GetLeafVariants().GetByOwner(consts.RunningIntentName) + if running == nil || running.GetDeleteFlag() { + return + } + if isCryptDiscoveryMatch(winning.Value(), running.Value()) { + if kp := newKeylessLeafPath(entry.SdcpbPath()); kp != "" { + transient[kp] = struct{}{} + } + } + }) + if len(transient) == 0 { + return noop + } + tc := root.GetTreeContext() + tc.SetLearnedMutateOnWritePaths(learnedPathOverlay{ + base: d.confirmedApplied, + transient: transient, + }) + return func() { + tc.SetLearnedMutateOnWritePaths(d.confirmedApplied) + } +} + +// evictStaleBaselines removes baselines or pending markers whose owner and +// intendedValue are no longer the active winning intended leaf in root. +func (d *Datastore) evictStaleBaselines(ctx context.Context, root *tree.RootEntry) { + if d == nil || d.confirmedApplied == nil || root == nil { + return + } + for _, id := range d.confirmedApplied.SnapshotIdentities() { + entry, err := ops.NavigateSdcpbPath(ctx, root.Entry, id.path) + if err != nil || entry == nil { + d.confirmedApplied.DeleteIdentity(id) + continue + } + winning := entry.GetLeafVariants().ActiveIntendedWinner() + if winning == nil || !id.matches(winning.Owner(), winning.Value()) { + d.confirmedApplied.DeleteIdentity(id) + } + } +} + +// capturePreTransactionBaselines records pre-transaction baselines and southbound +// paths before a forward TransactionSet mutates confirmedApplied. Callers must hold dmutex. +func (d *Datastore) capturePreTransactionBaselines(updates api.LeafVariantSlice, deletes treetypes.DeleteEntriesList) { + d.preTxBaselineSnap = d.confirmedApplied.Snapshot() + d.preTxTouchedPaths = collectSouthboundLeafAndDeleteKeys(updates, deletes) +} + +// restoreRolledBackBaselines restores untouched Non-revertive baselines and +// rolls back unconfirmed PreviouslyApplied path learning when a TransactionSet +// is canceled or expires. Callers must hold dmutex. +func (d *Datastore) restoreRolledBackBaselines( + ctx context.Context, + root *tree.RootEntry, + rollbackUpdates api.LeafVariantSlice, + rollbackDeletes treetypes.DeleteEntriesList, +) { + snap := d.preTxBaselineSnap + forwardTouched := d.preTxTouchedPaths + d.preTxBaselineSnap = nil + d.preTxTouchedPaths = nil + if snap == nil || root == nil { + return + } + + rollbackTouched := collectSouthboundLeafAndDeleteKeys(rollbackUpdates, rollbackDeletes) + deletePrefixes := deletesToPaths(rollbackDeletes) + + d.confirmedApplied.RestoreOnRollback( + snap, + func(path *sdcpb.Path) bool { + key := newCanonicalLeafPath(path) + if _, ok := forwardTouched[key]; ok { + return true + } + if _, ok := rollbackTouched[key]; ok { + return true + } + return pathCoveredBySync(path, deletePrefixes) + }, + func(id baselineIdentity) bool { + entry, err := ops.NavigateSdcpbPath(ctx, root.Entry, id.path) + if err != nil || entry == nil { + return false + } + winning := entry.GetLeafVariants().ActiveIntendedWinner() + return winning != nil && id.matches(winning.Owner(), winning.Value()) + }, + ) +} + +func collectSouthboundLeafAndDeleteKeys(updates api.LeafVariantSlice, deletes treetypes.DeleteEntriesList) map[canonicalLeafPath]struct{} { + if len(updates) == 0 && len(deletes) == 0 { + return nil + } + keys := make(map[canonicalLeafPath]struct{}, len(updates)+len(deletes)) + for _, le := range updates { + keys[newCanonicalLeafPath(le.SdcpbPath())] = struct{}{} + } + for _, del := range deletes { + keys[newCanonicalLeafPath(del.SdcpbPath())] = struct{}{} + } + return keys +} + +func deletesToPaths(deletes treetypes.DeleteEntriesList) []*sdcpb.Path { + if len(deletes) == 0 { + return nil + } + paths := make([]*sdcpb.Path, 0, len(deletes)) + for _, del := range deletes { + paths = append(paths, del.SdcpbPath()) + } + return paths +} + +// seedPreviouslyAppliedBaselines seeds confirmed applied values from live +// Running (or defers seeding until initial sync when path has not yet synced) for +// unpushed leaves won by PreviouslyApplied Non-revertive intents. Acquires +// syncTreeMutex for reading; callers must hold dmutex and not syncTreeMutex. +func (d *Datastore) seedPreviouslyAppliedBaselines( + root *tree.RootEntry, + newIntents map[string]*types.TransactionIntent, + pushedUpdates api.LeafVariantSlice, +) { + if d == nil || d.confirmedApplied == nil || root == nil { + return + } + eligibleOwners := eligiblePreviouslyAppliedOwners(newIntents) + if len(eligibleOwners) == 0 { + return + } + + pushed := make(map[canonicalLeafPath]struct{}, len(pushedUpdates)) + for _, le := range pushedUpdates { + pushed[newCanonicalLeafPath(le.SdcpbPath())] = struct{}{} + } + + d.syncTreeMutex.RLock() + defer d.syncTreeMutex.RUnlock() + + walkEligibleNonRevertiveWinners(root, eligibleOwners, func(entry api.Entry, winning *api.LeafEntry) { + path := entry.SdcpbPath() + if _, wasPushed := pushed[newCanonicalLeafPath(path)]; wasPushed { + return + } + if runningVal := d.runningValueLocked(path); runningVal != nil { + d.seedLeafBaselineFromRunning(winning, runningVal) + return + } + if pathCoveredBySync(path, d.syncedPaths) { + d.confirmedApplied.Delete(path) + return + } + if _, ok := baselineSeedingMode(winning); !ok { + d.confirmedApplied.Delete(path) + return + } + d.armInitialSyncSeed(winning, false) + }) +} + +func eligiblePreviouslyAppliedOwners(newIntents map[string]*types.TransactionIntent) map[string]struct{} { + var eligible map[string]struct{} + for _, intent := range newIntents { + if !intent.GetDeleteFlag() && intent.NonRevertive() && intent.GetPreviouslyApplied() { + if eligible == nil { + eligible = make(map[string]struct{}) + } + eligible[intent.GetName()] = struct{}{} + } + } + return eligible +} + +// baselineSeedingMode classifies winning from its static YANG schema rather +// than dynamically learned paths so unannotated string siblings still require +// crypt/cipher verification and pre-hashed plain strings never seed baselines. +func baselineSeedingMode(winning *api.LeafEntry) (baselineMode, bool) { + if winning == nil || winning.GetEntry() == nil { + return 0, false + } + if winning.GetEntry().GetSchema().IsMutateOnWrite() { + return modeMutateOnWrite, true + } + if isPlainStringLeafEntry(winning) && !matchesCryptOrCipherValue(winning.Value()) { + return modeCryptDiscovery, true + } + return 0, false +} + +func leafBaselineIdentity(winning *api.LeafEntry) baselineIdentity { + return baselineIdentity{ + path: winning.SdcpbPath(), + owner: winning.Owner(), + intendedValue: winning.Value(), + } +} + +// seedLeafBaselineFromRunning seeds winning's baseline from runningVal when +// winning qualifies for schema mutate-on-write or crypt discovery, evicting any +// prior baseline at winning's path otherwise. +func (d *Datastore) seedLeafBaselineFromRunning(winning *api.LeafEntry, runningVal *sdcpb.TypedValue) { + id := leafBaselineIdentity(winning) + mode, ok := baselineSeedingMode(winning) + if !ok { + d.confirmedApplied.Delete(id.path) + return + } + if mode == modeMutateOnWrite { + d.confirmedApplied.Record(id.path, id.owner, id.intendedValue, runningVal) + return + } + d.confirmedApplied.RecordDiscovered(id, runningVal) +} + +// armInitialSyncSeed registers winning for deferred baseline seeding on the +// first sync covering winning's path. When preserveExisting is true, an existing +// baseline or pending marker on that path is left intact. +func (d *Datastore) armInitialSyncSeed(winning *api.LeafEntry, preserveExisting bool) { + mode, ok := baselineSeedingMode(winning) + if !ok { + return + } + d.confirmedApplied.MarkAwaitingInitialSync(leafBaselineIdentity(winning), mode, preserveExisting) +} + +// runningValueLocked returns the live Running TypedValue at path, or nil when +// absent or marked deleted. Callers must hold syncTreeMutex (read or write). +func (d *Datastore) runningValueLocked(path *sdcpb.Path) *sdcpb.TypedValue { + if d.syncTree == nil || d.syncTree.Entry == nil { + return nil + } + syncEntry := ops.NavigateChildMap(d.syncTree.Entry, canonicalPath(path)) + if syncEntry == nil { + return nil + } + running := syncEntry.GetLeafVariants().GetByOwner(consts.RunningIntentName) + if running == nil || running.GetDeleteFlag() { + return nil + } + return running.Value() +} + +func walkEligibleNonRevertiveWinners( + root *tree.RootEntry, + eligibleOwners map[string]struct{}, + visit func(entry api.Entry, winning *api.LeafEntry), +) { + tc := root.GetTreeContext() + walkActiveIntendedWinners(root.Entry, func(entry api.Entry, winning *api.LeafEntry) { + if _, ok := eligibleOwners[winning.Owner()]; !ok { + return + } + if !tc.NonRevertiveInfo().IsNonRevertive(winning.Owner(), entry) { + return + } + visit(entry, winning) + }) +} + +func walkActiveIntendedWinners(entry api.Entry, visit func(entry api.Entry, winning *api.LeafEntry)) { + if entry == nil { + return + } + if winning := entry.GetLeafVariants().ActiveIntendedWinner(); winning != nil { + visit(entry, winning) + } + for _, child := range entry.GetChilds(treetypes.DescendMethodActiveChilds) { + walkActiveIntendedWinners(child, visit) + } +} diff --git a/pkg/datastore/confirmed_applied_values.go b/pkg/datastore/confirmed_applied_values.go index c3270633..76353a83 100644 --- a/pkg/datastore/confirmed_applied_values.go +++ b/pkg/datastore/confirmed_applied_values.go @@ -15,6 +15,7 @@ package datastore import ( + "maps" "slices" "strings" "sync" @@ -33,36 +34,79 @@ type canonicalLeafPath string // for a leaf's schema path across all list instances. type keylessLeafPath string -type captureMode uint8 +type baselineMode uint8 const ( - captureConfirmed captureMode = iota - capturePendingMutateOnWrite - capturePendingCryptDiscovery + modeConfirmed baselineMode = iota + modeMutateOnWrite + modeCryptDiscovery ) +// baselineIdentity identifies the winning intent state to which a confirmed +// applied value or pending capture epoch is bound. +type baselineIdentity struct { + path *sdcpb.Path + owner string + intendedValue *sdcpb.TypedValue +} + +func cloneBaselineIdentity(id baselineIdentity) baselineIdentity { + return baselineIdentity{ + path: proto.Clone(id.path).(*sdcpb.Path), + owner: id.owner, + intendedValue: proto.Clone(id.intendedValue).(*sdcpb.TypedValue), + } +} + +func (id baselineIdentity) matches(owner string, intendedValue *sdcpb.TypedValue) bool { + return id.owner == owner && api.TypedValuesEqual(id.intendedValue, intendedValue) +} + type confirmedAppliedEntry struct { - path *sdcpb.Path - owner string - intendedValue *sdcpb.TypedValue - confirmedValue *sdcpb.TypedValue - pendingCaptureAt int64 - mode captureMode + baselineIdentity + confirmedValue *sdcpb.TypedValue + captureAfterNano int64 + awaitingInitialSyncSeed bool + mode baselineMode } -// causalCaptureEpoch is a snapshot of one mutate-on-write write epoch. Completed -// epochs retain confirmedValue so older in-flight syncs can be ignored. +func cloneConfirmedAppliedEntry(e confirmedAppliedEntry) confirmedAppliedEntry { + out := confirmedAppliedEntry{ + baselineIdentity: cloneBaselineIdentity(e.baselineIdentity), + captureAfterNano: e.captureAfterNano, + awaitingInitialSyncSeed: e.awaitingInitialSyncSeed, + mode: e.mode, + } + if e.confirmedValue != nil { + out.confirmedValue = proto.Clone(e.confirmedValue).(*sdcpb.TypedValue) + } + return out +} + +// causalCaptureEpoch is an immutable snapshot of one mutate-on-write write or +// recovery epoch. Completed write epochs retain confirmedValue so older +// in-flight syncs can be ignored. type causalCaptureEpoch struct { - path *sdcpb.Path - owner string - intendedValue *sdcpb.TypedValue - confirmedValue *sdcpb.TypedValue - captureAfterNano int64 - mode captureMode + confirmedAppliedEntry } func (e causalCaptureEpoch) IsPending() bool { - return e.mode != captureConfirmed + return e.mode != modeConfirmed +} + +func (e causalCaptureEpoch) IsAwaitingInitialSync() bool { + return e.IsPending() && e.awaitingInitialSyncSeed +} + +// BlocksSync reports whether this write epoch postdates syncStartedAt and must +// keep older in-flight sync snapshots from overwriting Running or capturing stale data. +func (e causalCaptureEpoch) BlocksSync(syncStartedAt int64) bool { + return !e.awaitingInitialSyncSeed && syncStartedAt < e.captureAfterNano +} + +type confirmedAppliedSnapshot struct { + entries map[canonicalLeafPath]confirmedAppliedEntry + learnedPaths map[keylessLeafPath]struct{} } // confirmedAppliedValues holds the datastore's in-memory drift baselines and @@ -92,10 +136,7 @@ func (s *confirmedAppliedValues) Lookup(path *sdcpb.Path, winningOwner string, i s.mu.RLock() entry, ok := s.entries[key] s.mu.RUnlock() - if !ok || entry.confirmedValue == nil { - return nil - } - if entry.owner != winningOwner || !api.TypedValuesEqual(entry.intendedValue, intendedValue) { + if !ok || entry.confirmedValue == nil || !entry.matches(winningOwner, intendedValue) { return nil } return proto.Clone(entry.confirmedValue).(*sdcpb.TypedValue) @@ -105,69 +146,116 @@ func (s *confirmedAppliedValues) Lookup(path *sdcpb.Path, winningOwner string, i // when confirmedValue is non-empty. If intendedValue already matches the // crypt/cipher allowlist and confirmedValue differs, any baseline for path is evicted. func (s *confirmedAppliedValues) Record(path *sdcpb.Path, owner string, intendedValue, confirmedValue *sdcpb.TypedValue) { - s.record(path, owner, intendedValue, confirmedValue, 0) + s.record(baselineIdentity{path: path, owner: owner, intendedValue: intendedValue}, confirmedValue, 0) } // RecordAfter stores a baseline and the write completion barrier that older // in-flight sync snapshots must not cross, or evicts any baseline for path when // a pre-hashed intendedValue differs from confirmedValue. func (s *confirmedAppliedValues) RecordAfter(path *sdcpb.Path, owner string, intendedValue, confirmedValue *sdcpb.TypedValue, captureAfterNano int64) { - s.record(path, owner, intendedValue, confirmedValue, captureAfterNano) + s.record(baselineIdentity{path: path, owner: owner, intendedValue: intendedValue}, confirmedValue, captureAfterNano) +} + +// RecordDiscovered seeds a baseline for an unannotated plain string leaf only +// when confirmedValue matches a recognized crypt/cipher format and intendedValue +// does not, learning the leaf's keyless schema path on match and evicting any +// prior baseline for path otherwise. +func (s *confirmedAppliedValues) RecordDiscovered(id baselineIdentity, confirmedValue *sdcpb.TypedValue) { + if s == nil || id.path == nil || id.owner == "" || id.intendedValue == nil { + return + } + key := newCanonicalLeafPath(id.path) + s.mu.Lock() + s.recordDiscoveredLocked(key, cloneBaselineIdentity(id), confirmedValue, 0) + s.mu.Unlock() } -func (s *confirmedAppliedValues) record(path *sdcpb.Path, owner string, intendedValue, confirmedValue *sdcpb.TypedValue, captureAfterNano int64) { - if s == nil || path == nil || owner == "" || intendedValue == nil || !isNonEmptyTypedValue(confirmedValue) { +func (s *confirmedAppliedValues) recordDiscoveredLocked(key canonicalLeafPath, clonedID baselineIdentity, observed *sdcpb.TypedValue, captureAfterNano int64) { + if !isCryptDiscoveryMatch(clonedID.intendedValue, observed) { + delete(s.entries, key) return } - if rejectsPreHashedMismatch(intendedValue, confirmedValue) { - s.Delete(path) + s.entries[key] = confirmedAppliedEntry{ + baselineIdentity: clonedID, + confirmedValue: proto.Clone(observed).(*sdcpb.TypedValue), + captureAfterNano: captureAfterNano, + mode: modeConfirmed, + } + if kp := newKeylessLeafPath(clonedID.path); kp != "" { + s.learnedPaths[kp] = struct{}{} + } +} + +func (s *confirmedAppliedValues) record(id baselineIdentity, confirmedValue *sdcpb.TypedValue, captureAfterNano int64) { + if s == nil || id.path == nil || id.owner == "" || id.intendedValue == nil || !isNonEmptyTypedValue(confirmedValue) { return } - key := newCanonicalLeafPath(path) + if rejectsPreHashedMismatch(id.intendedValue, confirmedValue) { + s.Delete(id.path) + return + } + key := newCanonicalLeafPath(id.path) s.mu.Lock() - entry := confirmedAppliedEntry{ - path: proto.Clone(path).(*sdcpb.Path), - owner: owner, - intendedValue: proto.Clone(intendedValue).(*sdcpb.TypedValue), + s.entries[key] = confirmedAppliedEntry{ + baselineIdentity: cloneBaselineIdentity(id), confirmedValue: proto.Clone(confirmedValue).(*sdcpb.TypedValue), - pendingCaptureAt: captureAfterNano, - mode: captureConfirmed, + captureAfterNano: captureAfterNano, + mode: modeConfirmed, } - s.entries[key] = entry s.mu.Unlock() } // MarkPending retains the winning intent identity until a causally subsequent // sync can supply the confirmed target value. func (s *confirmedAppliedValues) MarkPending(path *sdcpb.Path, owner string, intendedValue *sdcpb.TypedValue, captureAfterNano int64) { - s.markPending(path, owner, intendedValue, captureAfterNano, capturePendingMutateOnWrite) + s.markPending(baselineIdentity{path: path, owner: owner, intendedValue: intendedValue}, captureAfterNano, modeMutateOnWrite) } // MarkDiscoveryCandidate records an unconfirmed push marker for an unannotated // plain string leaf whose first causal sync may reveal a crypt or cipher value. func (s *confirmedAppliedValues) MarkDiscoveryCandidate(path *sdcpb.Path, owner string, intendedValue *sdcpb.TypedValue, captureAfterNano int64) { - s.markPending(path, owner, intendedValue, captureAfterNano, capturePendingCryptDiscovery) + s.markPending(baselineIdentity{path: path, owner: owner, intendedValue: intendedValue}, captureAfterNano, modeCryptDiscovery) } -func (s *confirmedAppliedValues) markPending(path *sdcpb.Path, owner string, intendedValue *sdcpb.TypedValue, captureAfterNano int64, mode captureMode) { - if s == nil || path == nil || owner == "" || intendedValue == nil || captureAfterNano <= 0 { +// MarkAwaitingInitialSync defers baseline seeding for id until the first sync +// covering id.path completes. When preserveExisting is true, an existing +// baseline or pending marker at id.path is left intact. +func (s *confirmedAppliedValues) MarkAwaitingInitialSync(id baselineIdentity, mode baselineMode, preserveExisting bool) { + if s == nil || id.path == nil || id.owner == "" || id.intendedValue == nil || mode == modeConfirmed { return } - key := newCanonicalLeafPath(path) + key := newCanonicalLeafPath(id.path) + s.mu.Lock() + defer s.mu.Unlock() + if preserveExisting { + if _, exists := s.entries[key]; exists { + return + } + } + s.entries[key] = confirmedAppliedEntry{ + baselineIdentity: cloneBaselineIdentity(id), + awaitingInitialSyncSeed: true, + mode: mode, + } +} + +func (s *confirmedAppliedValues) markPending(id baselineIdentity, captureAfterNano int64, mode baselineMode) { + if s == nil || id.path == nil || id.owner == "" || id.intendedValue == nil || captureAfterNano <= 0 { + return + } + key := newCanonicalLeafPath(id.path) s.mu.Lock() s.entries[key] = confirmedAppliedEntry{ - path: proto.Clone(path).(*sdcpb.Path), - owner: owner, - intendedValue: proto.Clone(intendedValue).(*sdcpb.TypedValue), - pendingCaptureAt: captureAfterNano, + baselineIdentity: cloneBaselineIdentity(id), + captureAfterNano: captureAfterNano, mode: mode, } s.mu.Unlock() } -// CausalCaptures returns write epochs that still guard against older syncs. -// Pending entries also need the first causally subsequent observation. +// CausalCaptures returns write epochs that guard against older syncs plus +// pending post-Set or initial-sync seed epochs awaiting observation. func (s *confirmedAppliedValues) CausalCaptures() []causalCaptureEpoch { if s == nil { return nil @@ -176,28 +264,19 @@ func (s *confirmedAppliedValues) CausalCaptures() []causalCaptureEpoch { defer s.mu.RUnlock() result := make([]causalCaptureEpoch, 0) for _, entry := range s.entries { - if entry.pendingCaptureAt == 0 { + if entry.captureAfterNano == 0 && !entry.awaitingInitialSyncSeed { continue } - result = append(result, causalCaptureEpoch{ - path: proto.Clone(entry.path).(*sdcpb.Path), - owner: entry.owner, - intendedValue: proto.Clone(entry.intendedValue).(*sdcpb.TypedValue), - captureAfterNano: entry.pendingCaptureAt, - mode: entry.mode, - }) - if entry.confirmedValue != nil { - result[len(result)-1].confirmedValue = proto.Clone(entry.confirmedValue).(*sdcpb.TypedValue) - } + result = append(result, causalCaptureEpoch{confirmedAppliedEntry: cloneConfirmedAppliedEntry(entry)}) } return result } -// CompletePending resolves pending against the first causally subsequent -// observation: crypt-discovery epochs bind matching crypt/cipher observations -// and permanently learn the leaf's keyless schema path, mutate-on-write epochs -// bind non-empty observations unless a pre-hashed intendedValue differs, and -// non-matching or missing observations evict the epoch. +// CompletePending resolves pending against the first covering observation: +// crypt-discovery epochs bind matching crypt/cipher observations and permanently +// learn the leaf's keyless schema path, mutate-on-write epochs bind non-empty +// observations unless a pre-hashed intendedValue differs, and non-matching or +// missing observations evict the epoch. func (s *confirmedAppliedValues) CompletePending(pending causalCaptureEpoch, observed *sdcpb.TypedValue) { if s == nil || !pending.IsPending() { return @@ -206,21 +285,13 @@ func (s *confirmedAppliedValues) CompletePending(pending causalCaptureEpoch, obs s.mu.Lock() defer s.mu.Unlock() entry, ok := s.entries[key] - if !ok || entry.mode != pending.mode || entry.pendingCaptureAt != pending.captureAfterNano || - entry.owner != pending.owner || !api.TypedValuesEqual(entry.intendedValue, pending.intendedValue) { + if !ok || entry.mode != pending.mode || entry.captureAfterNano != pending.captureAfterNano || + entry.awaitingInitialSyncSeed != pending.awaitingInitialSyncSeed || + !entry.matches(pending.owner, pending.intendedValue) { return } - if pending.mode == capturePendingCryptDiscovery { - if !isCryptDiscoveryMatch(pending.intendedValue, observed) { - delete(s.entries, key) - return - } - entry.confirmedValue = proto.Clone(observed).(*sdcpb.TypedValue) - entry.mode = captureConfirmed - s.entries[key] = entry - if kp := newKeylessLeafPath(pending.path); kp != "" { - s.learnedPaths[kp] = struct{}{} - } + if pending.mode == modeCryptDiscovery { + s.recordDiscoveredLocked(key, entry.baselineIdentity, observed, entry.captureAfterNano) return } if !isNonEmptyTypedValue(observed) || rejectsPreHashedMismatch(pending.intendedValue, observed) { @@ -228,10 +299,64 @@ func (s *confirmedAppliedValues) CompletePending(pending causalCaptureEpoch, obs return } entry.confirmedValue = proto.Clone(observed).(*sdcpb.TypedValue) - entry.mode = captureConfirmed + entry.awaitingInitialSyncSeed = false + entry.mode = modeConfirmed s.entries[key] = entry } +// Snapshot captures a deep copy of all stored baselines and learned keyless +// paths so an unconfirmed transaction can restore untouched state on rollback. +func (s *confirmedAppliedValues) Snapshot() *confirmedAppliedSnapshot { + if s == nil { + return nil + } + s.mu.RLock() + defer s.mu.RUnlock() + entries := make(map[canonicalLeafPath]confirmedAppliedEntry, len(s.entries)) + for k, v := range s.entries { + entries[k] = cloneConfirmedAppliedEntry(v) + } + return &confirmedAppliedSnapshot{ + entries: entries, + learnedPaths: maps.Clone(s.learnedPaths), + } +} + +// RestoreOnRollback reverts learnedPaths to snap (preserving any paths confirmed +// by live write epochs) and restores untouched pre-transaction entries whose +// owner and intendedValue are once again active. +func (s *confirmedAppliedValues) RestoreOnRollback( + snap *confirmedAppliedSnapshot, + isTouched func(path *sdcpb.Path) bool, + isActiveWinner func(id baselineIdentity) bool, +) { + if s == nil || snap == nil { + return + } + s.mu.Lock() + defer s.mu.Unlock() + + restoredLearned := maps.Clone(snap.learnedPaths) + for _, entry := range s.entries { + if entry.mode == modeConfirmed && entry.captureAfterNano > 0 { + if kp := newKeylessLeafPath(entry.path); kp != "" { + restoredLearned[kp] = struct{}{} + } + } + } + s.learnedPaths = restoredLearned + + for key, prev := range snap.entries { + if _, exists := s.entries[key]; exists { + continue + } + if isTouched(prev.path) || !isActiveWinner(prev.baselineIdentity) { + continue + } + s.entries[key] = cloneConfirmedAppliedEntry(prev) + } +} + // DeleteSubtree removes stored baselines or pending markers at or below prefix. func (s *confirmedAppliedValues) DeleteSubtree(prefix *sdcpb.Path) { if s == nil || prefix == nil { @@ -258,6 +383,38 @@ func (s *confirmedAppliedValues) Delete(path *sdcpb.Path) { s.mu.Unlock() } +// SnapshotIdentities returns cloned identities for all currently stored baselines +// and pending capture markers. +func (s *confirmedAppliedValues) SnapshotIdentities() []baselineIdentity { + if s == nil { + return nil + } + s.mu.RLock() + defer s.mu.RUnlock() + if len(s.entries) == 0 { + return nil + } + out := make([]baselineIdentity, 0, len(s.entries)) + for _, entry := range s.entries { + out = append(out, cloneBaselineIdentity(entry.baselineIdentity)) + } + return out +} + +// DeleteIdentity removes the entry at id.path only when its stored owner and +// intendedValue still match id. +func (s *confirmedAppliedValues) DeleteIdentity(id baselineIdentity) { + if s == nil || id.path == nil { + return + } + key := newCanonicalLeafPath(id.path) + s.mu.Lock() + if entry, ok := s.entries[key]; ok && entry.matches(id.owner, id.intendedValue) { + delete(s.entries, key) + } + s.mu.Unlock() +} + // ClearAll removes all stored baselines. func (s *confirmedAppliedValues) ClearAll() { if s == nil { diff --git a/pkg/datastore/datastore_rpc.go b/pkg/datastore/datastore_rpc.go index d1c98d3b..60ed8739 100644 --- a/pkg/datastore/datastore_rpc.go +++ b/pkg/datastore/datastore_rpc.go @@ -69,11 +69,22 @@ type Datastore struct { // TransactionManager transactionManager *types.TransactionManager - // SyncTree + // SyncTree; syncTreeMutex guards both syncTree and syncedPaths. syncTree *tree.RootEntry syncTreeMutex *sync.RWMutex + syncedPaths []*sdcpb.Path + + // coldStartMu guards one-shot registration of pre-existing Non-revertive + // intents from cacheClient before the first sync or write transaction. + coldStartMu sync.Mutex + coldStartLoaded bool confirmedApplied *confirmedAppliedValues + // preTxBaselineSnap and preTxTouchedPaths hold the pre-transaction baseline + // snapshot and southbound-touched paths for an unconfirmed TransactionSet + // so TransactionRollback can restore untouched Non-revertive baselines; guarded by dmutex. + preTxBaselineSnap *confirmedAppliedSnapshot + preTxTouchedPaths map[canonicalLeafPath]struct{} taskPool *pool.SharedTaskPool } diff --git a/pkg/datastore/mutate_on_write_test.go b/pkg/datastore/mutate_on_write_test.go index eafe4d26..aca31e00 100644 --- a/pkg/datastore/mutate_on_write_test.go +++ b/pkg/datastore/mutate_on_write_test.go @@ -42,6 +42,7 @@ import ( "github.com/sdcio/data-server/pkg/utils/testhelper" "github.com/sdcio/schema-server/pkg/store/memstore" sdcpb "github.com/sdcio/sdc-protos/sdcpb" + "github.com/sdcio/sdc-protos/tree_persist" "go.uber.org/mock/gomock" "google.golang.org/grpc" "google.golang.org/grpc/peer" @@ -113,6 +114,23 @@ func initMutateOnWriteSchema(t *testing.T) (schema.Client, *config.SchemaConfig) } } } + choice auth-mode { + case primary { + leaf primary-auth { + type ianach:crypt-hash; + } + } + case fallback { + leaf fallback-auth { + type ianach:crypt-hash; + } + } + } + } + container extra { + leaf token { + type ianach:crypt-hash; + } } } `, @@ -227,15 +245,26 @@ func newMOWDatastoreFixture(t *testing.T, ctrl *gomock.Controller) *mowDatastore } func buildJSONIntent(t *testing.T, ds *Datastore, name string, prio int32, nonRevertive bool, payload map[string]any) *types.TransactionIntent { + t.Helper() + return buildJSONIntentWithOpts(t, ds, name, prio, nonRevertive, false, payload) +} + +func buildPreviouslyAppliedJSONIntent(t *testing.T, ds *Datastore, name string, prio int32, nonRevertive bool, payload map[string]any) *types.TransactionIntent { + t.Helper() + return buildJSONIntentWithOpts(t, ds, name, prio, nonRevertive, true, payload) +} + +func buildJSONIntentWithOpts(t *testing.T, ds *Datastore, name string, prio int32, nonRevertive bool, previouslyApplied bool, payload map[string]any) *types.TransactionIntent { t.Helper() raw, err := json.Marshal(payload) if err != nil { t.Fatalf("marshal payload: %v", err) } ti, err := ds.SdcpbTransactionIntentToInternalTI(context.Background(), &sdcpb.TransactionIntent{ - Intent: name, - Priority: prio, - NonRevertive: nonRevertive, + Intent: name, + Priority: prio, + NonRevertive: nonRevertive, + PreviouslyApplied: previouslyApplied, Update: []*sdcpb.Update{{ Path: &sdcpb.Path{}, Value: &sdcpb.TypedValue{ @@ -1297,33 +1326,31 @@ func TestDatastore_MutateOnWrite_BaselineKeySpecificityAndOverruled(t *testing.T }, }, }) - if _, err := f.ds.TransactionSet(ctx, "tx-2", []*types.TransactionIntent{highIntentV2}, nil, time.Minute, false); err != nil { + midNonRevertiveIntent := buildJSONIntent(t, f.ds, "mid-nr-owner", 15, true, map[string]any{ + "system": map[string]any{ + "user": []any{ + map[string]any{"username": "alice", "password": "HighSecretV2"}, + }, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-2", []*types.TransactionIntent{highIntentV2, midNonRevertiveIntent}, nil, time.Minute, false); err != nil { t.Fatalf("TransactionSet(tx-2): %v", err) } if err := f.ds.TransactionConfirm(ctx, "tx-2"); err != nil { t.Fatalf("TransactionConfirm(tx-2): %v", err) } - // PreviouslyApplied super-owner changes winningOwner without pushing, proving baseline owner specificity. - superIntent, err := f.ds.SdcpbTransactionIntentToInternalTI(ctx, &sdcpb.TransactionIntent{ - Intent: "super-owner", - Priority: 5, - NonRevertive: true, - PreviouslyApplied: true, - Update: []*sdcpb.Update{{ - Path: &sdcpb.Path{}, - Value: &sdcpb.TypedValue{ - Value: &sdcpb.TypedValue_JsonIetfVal{ - JsonIetfVal: []byte(`{"system":{"user":[{"username":"alice","password":"HighSecretV2"}]}}`), - }, + // Demoting high-owner below mid-nr-owner promotes an already-persisted non-revertive + // owner with the identical intended value without pushing, proving baseline owner specificity. + demotedHighIntent := buildJSONIntent(t, f.ds, "high-owner", 25, false, map[string]any{ + "system": map[string]any{ + "user": []any{ + map[string]any{"username": "alice", "password": "HighSecretV2"}, }, - }}, + }, }) - if err != nil { - t.Fatalf("SdcpbTransactionIntentToInternalTI(super-owner): %v", err) - } expectEmptySet(t, f.sbi) - if _, err := f.ds.TransactionSet(ctx, "tx-3", []*types.TransactionIntent{superIntent}, nil, time.Minute, false); err != nil { + if _, err := f.ds.TransactionSet(ctx, "tx-3", []*types.TransactionIntent{demotedHighIntent}, nil, time.Minute, false); err != nil { t.Fatalf("TransactionSet(tx-3): %v", err) } if err := f.ds.TransactionConfirm(ctx, "tx-3"); err != nil { @@ -1331,20 +1358,20 @@ func TestDatastore_MutateOnWrite_BaselineKeySpecificityAndOverruled(t *testing.T } eventsAfterOwnerChange := collectWatchDeviationsBatch(t, f.ds) - foundNotAppliedForSuper := false + foundNotAppliedForPromoted := false for _, ev := range eventsAfterOwnerChange { if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && - ev.GetIntent() == "super-owner" && + ev.GetIntent() == "mid-nr-owner" && ev.GetPath().ToXPath(false) == "/system/user[username=alice]/password" { - foundNotAppliedForSuper = true + foundNotAppliedForPromoted = true if ev.GetExpectedValue().GetStringVal() != "HighSecretV2" { t.Fatalf("NOT_APPLIED ExpectedValue = %v, want HighSecretV2", ev.GetExpectedValue()) } } } - if !foundNotAppliedForSuper { - t.Fatalf("expected NOT_APPLIED for super-owner because baseline belonged to high-owner, got %v", eventsAfterOwnerChange) + if !foundNotAppliedForPromoted { + t.Fatalf("expected NOT_APPLIED for mid-nr-owner because baseline belonged to high-owner, got %v", eventsAfterOwnerChange) } } @@ -2661,3 +2688,1415 @@ func TestDatastore_MutateOnWrite_UnannotatedNonCryptDriftRevertsWithoutLearning( } }) } + +func TestDatastore_MutateOnWrite_PreviouslyAppliedImmediateSeedWhenRunningPresent(t *testing.T) { + ctx := context.Background() + + t.Run("seeds mutate-on-write and unannotated crypt leaves immediately when Running is present", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + const ( + cleartextPw = "RecoveredPw1!" + hashedPw = "$6$rec1$hashedpassword" + cleartextOverlay = "RecoveredOv1!" + hashedOverlay = "$6$rec2$hashedoverlay" + cleartextAlice = "RecoveredAlice1" + hashedAlice = "$6$rec3$hashedalice" + preHashedBobA = "$6$bobA$hashvalueA" + preHashedBobB = "$6$bobB$hashvalueB" + ) + + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "hashed-password": hashedPw, + "overlay-password": hashedOverlay, + "hostname": "drifted-plain-host", + "user": []any{ + map[string]any{"username": "alice", "secret": hashedAlice}, + map[string]any{"username": "bob", "secret": preHashedBobB}, + }, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(initial): %v", err) + } + + expectEmptySet(t, f.sbi) + recovered := buildPreviouslyAppliedJSONIntent(t, f.ds, "nr-recovered", 10, true, map[string]any{ + "system": map[string]any{ + "hashed-password": cleartextPw, + "overlay-password": cleartextOverlay, + "hostname": "router-1", + "user": []any{ + map[string]any{"username": "alice", "secret": cleartextAlice}, + map[string]any{"username": "bob", "secret": preHashedBobA}, + }, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-recover", []*types.TransactionIntent{recovered}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-recover): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-recover"); err != nil { + t.Fatalf("TransactionConfirm(tx-recover): %v", err) + } + + persistedBlob, err := f.localCache.InstanceIntentGet(ctx, f.ds.Name(), "nr-recovered") + if err != nil { + t.Fatalf("InstanceIntentGet(nr-recovered): %v", err) + } + rawBlob := persistedBlob.String() + for _, h := range []string{hashedPw, hashedOverlay, hashedAlice} { + if strings.Contains(rawBlob, h) { + t.Fatalf("persisted intent blob leaked seeded hash %q: %s", h, rawBlob) + } + } + + notAppliedPaths := map[string]bool{} + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + notAppliedPaths[ev.GetPath().ToXPath(false)] = true + } + } + for _, cleanPath := range []string{ + "/system/hashed-password", + "/system/overlay-password", + "/system/user[username=alice]/secret", + } { + if notAppliedPaths[cleanPath] { + t.Fatalf("unexpected NOT_APPLIED on seeded path %s (all NOT_APPLIED: %v)", cleanPath, notAppliedPaths) + } + } + if !notAppliedPaths["/system/hostname"] { + t.Fatalf("expected NOT_APPLIED on non-crypt drifted plain string /system/hostname, got %v", notAppliedPaths) + } + if !notAppliedPaths["/system/user[username=bob]/secret"] { + t.Fatalf("expected NOT_APPLIED on pre-hashed mismatch /system/user[username=bob]/secret, got %v", notAppliedPaths) + } + + blame, err := f.ds.BlameConfig(ctx, false) + if err != nil { + t.Fatalf("BlameConfig: %v", err) + } + for _, leaf := range []string{"hashed-password", "overlay-password"} { + el := testhelper.FindBlameElement(blame, "system", leaf) + if el == nil || el.GetDeviationValue() != nil { + t.Fatalf("BlameConfig %s = %v, want non-nil with nil DeviationValue", leaf, el) + } + } + }) + + t.Run("overruled PreviouslyApplied intent does not clobber higher-priority owner baseline", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + expectHashedPasswordSetAndReadback(t, f, "HighCleartext!", "$6$high$hash", nil) + high := buildJSONIntent(t, f.ds, "high-owner", 5, false, map[string]any{ + "system": map[string]any{"hashed-password": "HighCleartext!"}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-high", []*types.TransactionIntent{high}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-high): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-high"); err != nil { + t.Fatalf("TransactionConfirm(tx-high): %v", err) + } + + expectEmptySet(t, f.sbi) + overruledNR := buildPreviouslyAppliedJSONIntent(t, f.ds, "low-nr", 20, true, map[string]any{ + "system": map[string]any{"hashed-password": "LowCleartext!"}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-low-nr", []*types.TransactionIntent{overruledNR}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-low-nr): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-low-nr"); err != nil { + t.Fatalf("TransactionConfirm(tx-low-nr): %v", err) + } + + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + t.Fatalf("overruled PreviouslyApplied intent clobbered winning baseline: %v", ev) + } + } + }) +} + +func TestDatastore_MutateOnWrite_PreviouslyAppliedBeforeInitialSync(t *testing.T) { + ctx := context.Background() + + t.Run("replaying PreviouslyApplied before slow initial sync finishes seeds present leaves and preserves NOT_APPLIED on absent leaves", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + const ( + cleartextPw = "SlowSyncPw1!" + hashedPw = "$6$slow1$hashedpw" + cleartextAlice = "SlowSyncAlice1" + hashedAlice = "$6$slow2$hashedalice" + missingOverlayPw = "MissingOverlay1!" + ) + + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + + // Snapshot starts before control-plane recovery replays PreviouslyApplied. + slowSyncStartedAt := time.Now().UnixNano() + time.Sleep(time.Millisecond) + + expectEmptySet(t, f.sbi) + recovered := buildPreviouslyAppliedJSONIntent(t, f.ds, "nr-before-sync", 10, true, map[string]any{ + "system": map[string]any{ + "hashed-password": cleartextPw, + "overlay-password": missingOverlayPw, + "hostname": "router-1", + "user": []any{ + map[string]any{"username": "alice", "secret": cleartextAlice}, + }, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-before-sync", []*types.TransactionIntent{recovered}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-before-sync): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-before-sync"); err != nil { + t.Fatalf("TransactionConfirm(tx-before-sync): %v", err) + } + + // Unrelated incremental update before full sync finishes must not clear awaitingInitialSyncSeed. + if err := f.ds.ApplyToRunning(ctx, slowSyncStartedAt, nil, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "user": []any{ + map[string]any{"username": "other"}, + }, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(unrelated incremental): %v", err) + } + + // Slow initial sync completes: hashed-password and alice/secret are present, overlay-password is absent. + if err := f.ds.ApplyToRunning(ctx, slowSyncStartedAt, []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "hashed-password": hashedPw, + "hostname": "drifted-plain", + "user": []any{ + map[string]any{"username": "alice", "secret": hashedAlice}, + }, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(slow initial sync): %v", err) + } + + notApplied := map[string]*sdcpb.WatchDeviationResponse{} + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + notApplied[ev.GetPath().ToXPath(false)] = ev + } + } + for _, seededPath := range []string{"/system/hashed-password", "/system/user[username=alice]/secret"} { + if ev, bad := notApplied[seededPath]; bad { + t.Fatalf("unexpected NOT_APPLIED on deferred-seeded path %s: %v", seededPath, ev) + } + } + ovEv, hasMissingOverlay := notApplied["/system/overlay-password"] + if !hasMissingOverlay { + t.Fatalf("expected NOT_APPLIED on genuinely absent /system/overlay-password, got %v", notApplied) + } + if ovEv.GetCurrentValue() != nil || ovEv.GetExpectedValue().GetStringVal() != missingOverlayPw { + t.Fatalf("absent /system/overlay-password event = %v, want nil CurrentValue and ExpectedValue %q", ovEv, missingOverlayPw) + } + if _, hasDriftedHost := notApplied["/system/hostname"]; !hasDriftedHost { + t.Fatalf("expected NOT_APPLIED on non-crypt /system/hostname, got %v", notApplied) + } + + // awaitingInitialSyncSeed was cleared on /system/overlay-password when initial sync observed Running == nil, + // so a later out-of-band CLI password on that path must still raise NOT_APPLIED. + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "hashed-password": hashedPw, + "overlay-password": "$6$later-cli$unexpectedhash", + "hostname": "router-1", + "user": []any{ + map[string]any{"username": "alice", "secret": hashedAlice}, + }, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(later CLI overlay-password): %v", err) + } + + foundOverlayStillNotApplied := false + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && + ev.GetPath().ToXPath(false) == "/system/overlay-password" { + foundOverlayStillNotApplied = true + } + } + if !foundOverlayStillNotApplied { + t.Fatal("expected /system/overlay-password to remain NOT_APPLIED after later CLI edit because awaitingInitialSyncSeed was cleared") + } + }) + + t.Run("PreviouslyApplied after initial sync already confirmed leaf absent does not arm awaitingInitialSyncSeed", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + + // Initial sync completes first with hashed-password absent on target. + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hostname": "router-1"}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(initial empty): %v", err) + } + + expectEmptySet(t, f.sbi) + recovered := buildPreviouslyAppliedJSONIntent(t, f.ds, "nr-after-empty-sync", 10, true, map[string]any{ + "system": map[string]any{"hashed-password": "ShouldBeMissing1!"}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-after-empty-sync", []*types.TransactionIntent{recovered}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet: %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-after-empty-sync"); err != nil { + t.Fatalf("TransactionConfirm: %v", err) + } + + // Subsequent out-of-band CLI edit must NOT be auto-seeded as initial sync. + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "hostname": "router-1", + "hashed-password": "$6$cli$unrelatedhash", + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(later CLI): %v", err) + } + + foundNotApplied := false + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && + ev.GetPath().ToXPath(false) == "/system/hashed-password" { + foundNotApplied = true + } + } + if !foundNotApplied { + t.Fatal("expected NOT_APPLIED when leaf was already absent on initial sync and later edited via CLI") + } + }) +} + +type writeCountingCacheClient struct { + cache.CacheClientBound + modifyCalls int + deleteCalls int +} + +func (w *writeCountingCacheClient) IntentModify(ctx context.Context, intent *tree_persist.Intent) error { + w.modifyCalls++ + return w.CacheClientBound.IntentModify(ctx, intent) +} + +func (w *writeCountingCacheClient) IntentDelete(ctx context.Context, intentName string, ignoreNonExisting bool) error { + w.deleteCalls++ + return w.CacheClientBound.IntentDelete(ctx, intentName, ignoreNonExisting) +} + +func newColdRestartedDatastoreFromFixture(t *testing.T, ctrl *gomock.Controller, orig *mowDatastoreFixture) (*Datastore, *mocktarget.MockTarget, *writeCountingCacheClient) { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + + vpf := pool.NewSharedTaskPool(ctx, runtime.GOMAXPROCS(0)) + confirmed := newConfirmedAppliedValues() + tc := tree.NewTreeContext(orig.ds.schemaClient, vpf, tree.WithConfirmedAppliedValues(confirmed)) + syncTreeRoot, err := tree.NewTreeRoot(ctx, tc) + if err != nil { + t.Fatalf("NewTreeRoot(restarted): %v", err) + } + if err := syncTreeRoot.FinishInsertionPhase(ctx); err != nil { + t.Fatalf("FinishInsertionPhase(restarted): %v", err) + } + + wrappedCache := &writeCountingCacheClient{ + CacheClientBound: cache.NewCacheClientBound(orig.ds.Name(), orig.localCache), + } + sbi := mocktarget.NewMockTarget(ctrl) + restarted := &Datastore{ + config: orig.ds.config, + cacheClient: wrappedCache, + sbi: sbi, + schemaClient: orig.ds.schemaClient, + ctx: ctx, + cfn: cancel, + m: &sync.RWMutex{}, + deviationClients: make(map[sdcpb.DataServer_WatchDeviationsServer]string), + dmutex: &sync.Mutex{}, + syncTree: syncTreeRoot, + syncTreeMutex: &sync.RWMutex{}, + confirmedApplied: confirmed, + taskPool: vpf, + } + restarted.transactionManager = types.NewTransactionManager(NewDatastoreRollbackAdapter(restarted), types.WithAutoRollbackLock(restarted.dmutex)) + return restarted, sbi, wrappedCache +} + +func TestDatastore_MutateOnWrite_StandaloneColdStartFirstSyncSeedsFromCache(t *testing.T) { + ctx := context.Background() + + t.Run("first sync on restarted Datastore seeds pre-existing Non-revertive intents without writing to cacheClient", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + const ( + cleartextPw = "ColdStartPw1!" + hashedPw = "$6$cold1$hashedpw" + cleartextOverlay = "ColdStartOv1!" + hashedOverlay = "$6$cold2$hashedov" + cleartextAlice = "ColdStartAlice" + hashedAlice = "$6$cold3$hashedalice" + missingBobPw = "MissingBobPw1!" + ) + + // Author and confirm a Non-revertive intent on ds1 so localCache holds the persisted intent. + set1 := f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).After(set1).Return(&sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{ + { + Path: hashedPasswordPath(), + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: hashedPw}}, + }, + { + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("overlay-password", nil), + }}, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: hashedOverlay}}, + }, + { + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("user", map[string]string{"username": "bob"}), + sdcpb.NewPathElem("password", nil), + }}, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: "$6$bob$initial"}}, + }, + }, + }}, + }, nil).Times(1) + + nrIntent := buildJSONIntent(t, f.ds, "nr-persisted", 10, true, map[string]any{ + "system": map[string]any{ + "hashed-password": cleartextPw, + "overlay-password": cleartextOverlay, + "hostname": "router-1", + "user": []any{ + map[string]any{"username": "alice", "secret": cleartextAlice}, + map[string]any{"username": "bob", "password": missingBobPw}, + }, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-init", []*types.TransactionIntent{nrIntent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-init): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-init"); err != nil { + t.Fatalf("TransactionConfirm(tx-init): %v", err) + } + + beforeBlob, err := f.localCache.InstanceIntentGet(ctx, f.ds.Name(), "nr-persisted") + if err != nil { + t.Fatalf("InstanceIntentGet(before restart): %v", err) + } + beforeRaw := beforeBlob.String() + + // Simulate standalone Datastore cold restart pointing at the same localCache. + ds2, sbi2, cacheSpy := newColdRestartedDatastoreFromFixture(t, ctrl, f) + sbi2.EXPECT().Set(gomock.Any(), gomock.Any()).Times(0) + sbi2.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + + // Very first sync on ds2: hashed-password, overlay-password, and alice/secret are present; bob/password is missing. + if err := ds2.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "hashed-password": hashedPw, + "overlay-password": hashedOverlay, + "hostname": "router-1", + "user": []any{ + map[string]any{"username": "alice", "secret": hashedAlice}, + }, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ds2.ApplyToRunning(cold first sync): %v", err) + } + + if cacheSpy.modifyCalls != 0 || cacheSpy.deleteCalls != 0 { + t.Fatalf("cold-start sync wrote to cacheClient: modifyCalls=%d deleteCalls=%d, want 0/0", + cacheSpy.modifyCalls, cacheSpy.deleteCalls) + } + afterBlob, err := f.localCache.InstanceIntentGet(ctx, f.ds.Name(), "nr-persisted") + if err != nil { + t.Fatalf("InstanceIntentGet(after cold sync): %v", err) + } + if afterBlob.String() != beforeRaw { + t.Fatalf("persisted intent changed across cold-start sync:\nbefore: %s\nafter: %s", beforeRaw, afterBlob.String()) + } + + notApplied := map[string]bool{} + for _, ev := range collectWatchDeviationsBatch(t, ds2) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + notApplied[ev.GetPath().ToXPath(false)] = true + } + } + for _, cleanPath := range []string{ + "/system/hashed-password", + "/system/overlay-password", + "/system/user[username=alice]/secret", + } { + if notApplied[cleanPath] { + t.Fatalf("unexpected NOT_APPLIED after cold-start seed on %s (all: %v)", cleanPath, notApplied) + } + } + if !notApplied["/system/user[username=bob]/password"] { + t.Fatalf("expected NOT_APPLIED on missing /system/user[username=bob]/password, got %v", notApplied) + } + + // One-shot check: a second sync where bob/password suddenly appears via CLI must NOT seed bob/password. + if err := ds2.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "hashed-password": hashedPw, + "overlay-password": hashedOverlay, + "hostname": "router-1", + "user": []any{ + map[string]any{"username": "alice", "secret": hashedAlice}, + map[string]any{"username": "bob", "password": "$6$cli$bobunexpected"}, + }, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ds2.ApplyToRunning(second sync): %v", err) + } + + foundBobNotApplied := false + for _, ev := range collectWatchDeviationsBatch(t, ds2) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && + ev.GetPath().ToXPath(false) == "/system/user[username=bob]/password" { + foundBobNotApplied = true + } + } + if !foundBobNotApplied { + t.Fatal("expected second sync NOT to cold-seed missing bob/password after CLI edit") + } + }) + + t.Run("cold-start seeding does not suppress revertive intents", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + expectHashedPasswordSetAndReadback(t, f, "RevertivePw1!", "$6$rev$hash1", nil) + revIntent := buildJSONIntent(t, f.ds, "rev-persisted", 10, false, map[string]any{ + "system": map[string]any{"hashed-password": "RevertivePw1!"}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-rev", []*types.TransactionIntent{revIntent}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-rev): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-rev"); err != nil { + t.Fatalf("TransactionConfirm(tx-rev): %v", err) + } + + ds2, sbi2, _ := newColdRestartedDatastoreFromFixture(t, ctrl, f) + + // Pure cold start with a revertive intent in cacheClient must still run performRevert + targeted Get. + revSet := sbi2.EXPECT(). + Set(gomock.Any(), gomock.Any()). + DoAndReturn(func(setCtx context.Context, source targettypes.TargetSource) (*sdcpb.SetDataResponse, error) { + upds, err := source.ToProtoUpdates(setCtx, true) + if err != nil { + return nil, err + } + if got := updatesByXPath(upds)["/system/hashed-password"]; got != "RevertivePw1!" { + t.Fatalf("cold-start revert pushed hashed-password = %q, want RevertivePw1!", got) + } + return &sdcpb.SetDataResponse{}, nil + }).Times(1) + sbi2.EXPECT().Get(gomock.Any(), gomock.Any()).After(revSet).Return(&sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{{ + Path: hashedPasswordPath(), + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: "$6$rev$reapplied"}}, + }}, + }}, + }, nil).Times(1) + + if err := ds2.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": "$6$rev$hash1"}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ds2.ApplyToRunning: %v", err) + } + }) + + t.Run("cold-start first sync does not overwrite baseline already bound by live pre-sync TransactionSet", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + liveSet := f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).After(liveSet).Return(&sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("overlay-password", nil), + }}, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: "$6$live$ovhash1"}}, + }}, + }}, + }, nil).Times(1) + + liveNR := buildJSONIntent(t, f.ds, "nr-live", 10, true, map[string]any{ + "system": map[string]any{"overlay-password": "LiveOverlayPw!"}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-live", []*types.TransactionIntent{liveNR}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-live): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-live"); err != nil { + t.Fatalf("TransactionConfirm(tx-live): %v", err) + } + + // First sync on f.ds delivers a CLI-drifted hash after tx-live finished; preserveExisting keeps "$6$live$ovhash1". + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"overlay-password": "$6$cli$ovdrifted"}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning: %v", err) + } + + foundLiveDrift := false + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && + ev.GetPath().ToXPath(false) == "/system/overlay-password" { + foundLiveDrift = true + } + } + if !foundLiveDrift { + t.Fatal("expected cold-start first sync not to overwrite pre-existing in-memory baseline on /system/overlay-password") + } + }) +} + +func TestDatastore_MutateOnWrite_PostSeedOutOfBandDriftRaisesNotApplied(t *testing.T) { + ctx := context.Background() + + const ( + cleartextPw = "SeededPw1!" + seededPwHash = "$6$seed$pwhash" + driftedPwHash = "$6$cli$driftedpw" + cleartextAlice = "SeededAlice1" + seededAlice = "$6$seed$alicehash" + driftedAlice = "$6$cli$driftedalice" + ) + + modes := []struct { + name string + setup func(t *testing.T, ctrl *gomock.Controller) *Datastore + }{ + { + name: "PreviouslyApplied after initial sync", + setup: func(t *testing.T, ctrl *gomock.Controller) *Datastore { + f := newMOWDatastoreFixture(t, ctrl) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "hashed-password": seededPwHash, + "user": []any{ + map[string]any{"username": "alice", "secret": seededAlice}, + }, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(initial): %v", err) + } + expectEmptySet(t, f.sbi) + pa := buildPreviouslyAppliedJSONIntent(t, f.ds, "nr-intent", 10, true, map[string]any{ + "system": map[string]any{ + "hashed-password": cleartextPw, + "user": []any{ + map[string]any{"username": "alice", "secret": cleartextAlice}, + }, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-pa", []*types.TransactionIntent{pa}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-pa): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-pa"); err != nil { + t.Fatalf("TransactionConfirm(tx-pa): %v", err) + } + return f.ds + }, + }, + { + name: "PreviouslyApplied before initial sync", + setup: func(t *testing.T, ctrl *gomock.Controller) *Datastore { + f := newMOWDatastoreFixture(t, ctrl) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + expectEmptySet(t, f.sbi) + pa := buildPreviouslyAppliedJSONIntent(t, f.ds, "nr-intent", 10, true, map[string]any{ + "system": map[string]any{ + "hashed-password": cleartextPw, + "user": []any{ + map[string]any{"username": "alice", "secret": cleartextAlice}, + }, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-pa-pre", []*types.TransactionIntent{pa}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-pa-pre): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-pa-pre"); err != nil { + t.Fatalf("TransactionConfirm(tx-pa-pre): %v", err) + } + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "hashed-password": seededPwHash, + "user": []any{ + map[string]any{"username": "alice", "secret": seededAlice}, + }, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(initial): %v", err) + } + return f.ds + }, + }, + { + name: "standalone cold-start first sync from cacheClient", + setup: func(t *testing.T, ctrl *gomock.Controller) *Datastore { + f := newMOWDatastoreFixture(t, ctrl) + set1 := f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).After(set1).Return(&sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{{ + Path: hashedPasswordPath(), + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: seededPwHash}}, + }}, + }}, + }, nil).Times(1) + nr := buildJSONIntent(t, f.ds, "nr-intent", 10, true, map[string]any{ + "system": map[string]any{ + "hashed-password": cleartextPw, + "user": []any{ + map[string]any{"username": "alice", "secret": cleartextAlice}, + }, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-init", []*types.TransactionIntent{nr}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-init): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-init"); err != nil { + t.Fatalf("TransactionConfirm(tx-init): %v", err) + } + ds2, sbi2, _ := newColdRestartedDatastoreFromFixture(t, ctrl, f) + sbi2.EXPECT().Set(gomock.Any(), gomock.Any()).Times(0) + sbi2.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + if err := ds2.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "hashed-password": seededPwHash, + "user": []any{ + map[string]any{"username": "alice", "secret": seededAlice}, + }, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ds2.ApplyToRunning(first sync): %v", err) + } + return ds2 + }, + }, + } + + for _, mode := range modes { + t.Run(mode.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + ds := mode.setup(t, ctrl) + + // Baseline is converged immediately after seeding. + for _, ev := range collectWatchDeviationsBatch(t, ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + t.Fatalf("unexpected NOT_APPLIED right after seeding: %v", ev) + } + } + + // Out-of-band CLI edit changing Running away from seeded hashes must raise NOT_APPLIED. + if err := ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "hashed-password": driftedPwHash, + "user": []any{ + map[string]any{"username": "alice", "secret": driftedAlice}, + }, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(CLI value drift): %v", err) + } + + editedDevs := map[string]*sdcpb.WatchDeviationResponse{} + for _, ev := range collectWatchDeviationsBatch(t, ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + editedDevs[ev.GetPath().ToXPath(false)] = ev + } + } + pwDev := editedDevs["/system/hashed-password"] + if pwDev == nil || pwDev.GetExpectedValue().GetStringVal() != cleartextPw || pwDev.GetCurrentValue().GetStringVal() != driftedPwHash { + t.Fatalf("CLI edit deviation on /system/hashed-password = %v, want expected=%q current=%q", pwDev, cleartextPw, driftedPwHash) + } + aliceDev := editedDevs["/system/user[username=alice]/secret"] + if aliceDev == nil || aliceDev.GetExpectedValue().GetStringVal() != cleartextAlice || aliceDev.GetCurrentValue().GetStringVal() != driftedAlice { + t.Fatalf("CLI edit deviation on /system/user[username=alice]/secret = %v, want expected=%q current=%q", aliceDev, cleartextAlice, driftedAlice) + } + + // Out-of-band CLI deletion removing both leaves from Running must also raise NOT_APPLIED. + if err := ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hostname": "after-delete"}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(CLI delete): %v", err) + } + + deletedDevs := map[string]*sdcpb.WatchDeviationResponse{} + for _, ev := range collectWatchDeviationsBatch(t, ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + deletedDevs[ev.GetPath().ToXPath(false)] = ev + } + } + if d := deletedDevs["/system/hashed-password"]; d == nil || d.GetCurrentValue() != nil { + t.Fatalf("CLI delete deviation on /system/hashed-password = %v, want NOT_APPLIED with nil CurrentValue", d) + } + if d := deletedDevs["/system/user[username=alice]/secret"]; d == nil || d.GetCurrentValue() != nil { + t.Fatalf("CLI delete deviation on /system/user[username=alice]/secret = %v, want NOT_APPLIED with nil CurrentValue", d) + } + }) + } + + t.Run("cancelling unconfirmed PreviouslyApplied transaction before initial sync evicts awaitingInitialSyncSeed", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + expectEmptySet(t, f.sbi) + pa := buildPreviouslyAppliedJSONIntent(t, f.ds, "nr-cancelled", 15, true, map[string]any{ + "system": map[string]any{ + "user": []any{ + map[string]any{"username": "alice", "secret": "CancelledAlice1"}, + }, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-unconfirmed", []*types.TransactionIntent{pa}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-unconfirmed): %v", err) + } + + // Rollback while Running == nil sends an empty southbound diff and must evict awaitingInitialSyncSeed. + expectEmptySet(t, f.sbi) + if err := f.ds.TransactionCancel(ctx, "tx-unconfirmed"); err != nil { + t.Fatalf("TransactionCancel(tx-unconfirmed): %v", err) + } + + // Initial sync arrives with unmanaged alice secret on target; because tx-unconfirmed was cancelled, + // /system/user/secret must NOT be learned from the cancelled awaitingInitialSyncSeed entry. + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "user": []any{ + map[string]any{"username": "alice", "secret": "$6$unmanaged$alicehash"}, + }, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(initial): %v", err) + } + + // Subsequent TransactionSet on bob/secret must issue Set only and zero targeted Gets. + f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + + bob := buildJSONIntent(t, f.ds, "bob-intent", 10, false, map[string]any{ + "system": map[string]any{ + "user": []any{ + map[string]any{"username": "bob", "secret": "BobPlain1"}, + }, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-bob", []*types.TransactionIntent{bob}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-bob): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-bob"); err != nil { + t.Fatalf("TransactionConfirm(tx-bob): %v", err) + } + }) +} + +func TestDatastore_MutateOnWrite_PreviouslyAppliedLongCryptAndChoiceLeaf(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + const ( + longAliceHash = "$6$rounds=5000$alicesalt$0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + longUnmanagedHash = "$6$rounds=5000$othersalt$fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210" + primaryHash = "$6$choice$primaryhash" + fallbackHash = "$6$choice$fallbackhash" + ) + + aliceSecretPath := &sdcpb.Path{Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("user", map[string]string{"username": "alice"}), + sdcpb.NewPathElem("secret", nil), + }} + + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"primary-auth": primaryHash}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(primary): %v", err) + } + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "fallback-auth": fallbackHash, + "user": []any{ + map[string]any{"username": "alice", "secret": longAliceHash}, + map[string]any{"username": "bob", "secret": "DriftedPlainBob"}, + map[string]any{"username": "unmanaged", "secret": longUnmanagedHash}, + }, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(fallback + long crypt): %v", err) + } + + recoveredDryRun := buildPreviouslyAppliedJSONIntent(t, f.ds, "nr-choice-crypt", 10, true, map[string]any{ + "system": map[string]any{ + "fallback-auth": "ChoiceCleartext1!", + "user": []any{ + map[string]any{"username": "alice", "secret": "AlicePlain123"}, + map[string]any{"username": "bob", "secret": "BobPlain123"}, + }, + }, + }) + dryResp, err := f.ds.TransactionSet(ctx, "tx-dry", []*types.TransactionIntent{recoveredDryRun}, nil, time.Minute, true) + if err != nil { + t.Fatalf("TransactionSet(dryRun) err = %v", err) + } + if len(dryResp.GetErrors()) != 0 { + t.Fatalf("TransactionSet(dryRun) validation errors = %v, want none", dryResp.GetErrors()) + } + if f.ds.confirmedApplied.IsLearnedMutateOnWritePath(aliceSecretPath) { + t.Fatal("dryRun must not mutate learned mutate-on-write paths") + } + + expectEmptySet(t, f.sbi) + recovered := buildPreviouslyAppliedJSONIntent(t, f.ds, "nr-choice-crypt", 10, true, map[string]any{ + "system": map[string]any{ + "fallback-auth": "ChoiceCleartext1!", + "user": []any{ + map[string]any{"username": "alice", "secret": "AlicePlain123"}, + map[string]any{"username": "bob", "secret": "BobPlain123"}, + }, + }, + }) + resp, err := f.ds.TransactionSet(ctx, "tx-commit", []*types.TransactionIntent{recovered}, nil, time.Minute, false) + if err != nil { + t.Fatalf("TransactionSet(commit) err = %v", err) + } + if len(resp.GetErrors()) != 0 { + t.Fatalf("TransactionSet(commit) validation errors = %v, want none", resp.GetErrors()) + } + if err := f.ds.TransactionConfirm(ctx, "tx-commit"); err != nil { + t.Fatalf("TransactionConfirm(tx-commit): %v", err) + } + + if !f.ds.confirmedApplied.IsLearnedMutateOnWritePath(aliceSecretPath) { + t.Fatal("commit of PreviouslyApplied crypt leaf must permanently learn keyless schema path") + } + + notApplied := map[string]bool{} + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + notApplied[ev.GetPath().ToXPath(false)] = true + } + } + if notApplied["/system/fallback-auth"] || notApplied["/system/user[username=alice]/secret"] { + t.Fatalf("unexpected NOT_APPLIED on choice or crypt leaf: %v", notApplied) + } + if !notApplied["/system/user[username=bob]/secret"] { + t.Fatalf("expected NOT_APPLIED on sibling bob with drifted non-crypt plain string, got %v", notApplied) + } + + // Subsequent live Set (without PreviouslyApplied) must pass validation against >32-char Running hashes + // and perform a post-Set readback on the learned user/secret path. + carolSecretPath := &sdcpb.Path{Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("user", map[string]string{"username": "carol"}), + sdcpb.NewPathElem("secret", nil), + }} + setCarol := f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).After(setCarol).Return(&sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{{ + Path: carolSecretPath, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: "$6$carol$hash"}}, + }}, + }}, + }, nil).Times(1) + liveCarol := buildJSONIntent(t, f.ds, "live-carol", 5, true, map[string]any{ + "system": map[string]any{ + "user": []any{ + map[string]any{"username": "carol", "secret": "CarolPlain123"}, + }, + }, + }) + liveResp, err := f.ds.TransactionSet(ctx, "tx-live-carol", []*types.TransactionIntent{liveCarol}, nil, time.Minute, false) + if err != nil { + t.Fatalf("TransactionSet(tx-live-carol): %v", err) + } + if len(liveResp.GetErrors()) != 0 { + t.Fatalf("TransactionSet(tx-live-carol) validation errors = %v, want none", liveResp.GetErrors()) + } + if err := f.ds.TransactionConfirm(ctx, "tx-live-carol"); err != nil { + t.Fatalf("TransactionConfirm(tx-live-carol): %v", err) + } +} + +func TestDatastore_MutateOnWrite_MultiSubtreeColdStartAndPostStartupIsolation(t *testing.T) { + ctx := context.Background() + + t.Run("multi-subtree cold start seeds each pre-existing Non-revertive subtree when its sync arrives", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + set1 := f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).After(set1).Return(&sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{ + { + Path: hashedPasswordPath(), + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: "$6$sys$hash"}}, + }, + { + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("extra", nil), + sdcpb.NewPathElem("token", nil), + }}, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: "$6$extra$hash"}}, + }, + }, + }}, + }, nil).Times(1) + + nr := buildJSONIntent(t, f.ds, "nr-multisub", 10, true, map[string]any{ + "system": map[string]any{"hashed-password": "SysSecret1!"}, + "extra": map[string]any{"token": "ExtraToken1!"}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-init", []*types.TransactionIntent{nr}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-init): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-init"); err != nil { + t.Fatalf("TransactionConfirm(tx-init): %v", err) + } + + ds2, sbi2, cacheSpy := newColdRestartedDatastoreFromFixture(t, ctrl, f) + sbi2.EXPECT().Set(gomock.Any(), gomock.Any()).Times(0) + sbi2.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + + // Subtree 1 (/extra) syncs first. + extraPath := []*sdcpb.Path{{IsRootBased: true, Elem: []*sdcpb.PathElem{sdcpb.NewPathElem("extra", nil)}}} + if err := ds2.ApplyToRunning(ctx, time.Now().UnixNano(), extraPath, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "extra": map[string]any{"token": "$6$extra$hash"}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(/extra): %v", err) + } + + // Subtree 2 (/system) syncs second: must ALSO seed /system/hashed-password cleanly. + sysPath := []*sdcpb.Path{{IsRootBased: true, Elem: []*sdcpb.PathElem{sdcpb.NewPathElem("system", nil)}}} + if err := ds2.ApplyToRunning(ctx, time.Now().UnixNano(), sysPath, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": "$6$sys$hash"}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(/system): %v", err) + } + + if cacheSpy.modifyCalls != 0 || cacheSpy.deleteCalls != 0 { + t.Fatalf("unexpected cache writes during multi-subtree cold start: modify=%d delete=%d", + cacheSpy.modifyCalls, cacheSpy.deleteCalls) + } + + for _, ev := range collectWatchDeviationsBatch(t, ds2) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + t.Fatalf("unexpected NOT_APPLIED after multi-subtree cold start: %v", ev) + } + } + }) + + t.Run("fresh empty-cache Datastore never cold-seeds post-startup promoted Non-revertive owners on first sync", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + expectHashedPasswordSetAndReadback(t, f, "HighPw1!", "$6$high$hash", nil) + high := buildJSONIntent(t, f.ds, "high-owner", 5, false, map[string]any{ + "system": map[string]any{"hashed-password": "HighPw1!"}, + }) + midNR := buildJSONIntent(t, f.ds, "mid-nr", 15, true, map[string]any{ + "system": map[string]any{"hashed-password": "MidOtherPw!"}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-1", []*types.TransactionIntent{high, midNR}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-1): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-1"); err != nil { + t.Fatalf("TransactionConfirm(tx-1): %v", err) + } + + // Demote high-owner before first sync runs so mid-nr becomes active without baseline. + expectEmptySet(t, f.sbi) + demoted := buildJSONIntent(t, f.ds, "high-owner", 25, false, map[string]any{ + "system": map[string]any{"hashed-password": "HighPw1!"}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-2", []*types.TransactionIntent{demoted}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-2): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-2"); err != nil { + t.Fatalf("TransactionConfirm(tx-2): %v", err) + } + + // First sync arrives on this fresh Datastore: mid-nr was NOT a cold-start intent and must report NOT_APPLIED. + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": "$6$high$hash"}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(first sync): %v", err) + } + + foundNotApplied := false + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && + ev.GetIntent() == "mid-nr" && + ev.GetPath().ToXPath(false) == "/system/hashed-password" { + foundNotApplied = true + } + } + if !foundNotApplied { + t.Fatal("expected post-startup promoted mid-nr not to be cold-seeded on first sync") + } + }) +} + +func TestDatastore_MutateOnWrite_InitialSyncCompletionClearsAbsentSeed(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + expectEmptySet(t, f.sbi) + + recovered := buildPreviouslyAppliedJSONIntent(t, f.ds, "nr-stream", 10, true, map[string]any{ + "system": map[string]any{ + "hashed-password": "StreamPresent1!", + "overlay-password": "StreamAbsent1!", + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-stream-pa", []*types.TransactionIntent{recovered}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet: %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-stream-pa"); err != nil { + t.Fatalf("TransactionConfirm: %v", err) + } + + if err := f.ds.ApplyInitialSync(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, nil, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": "$6$stream$present"}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyInitialSync: %v", err) + } + + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), nil, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"overlay-password": "$6$stream$latercli"}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(later stream CLI): %v", err) + } + + notApplied := map[string]bool{} + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + notApplied[ev.GetPath().ToXPath(false)] = true + } + } + if notApplied["/system/hashed-password"] { + t.Fatalf("unexpected NOT_APPLIED on /system/hashed-password: %v", notApplied) + } + if !notApplied["/system/overlay-password"] { + t.Fatalf("expected NOT_APPLIED on /system/overlay-password after initial stream sync confirmed it absent, got %v", notApplied) + } +} + +func TestDatastore_MutateOnWrite_CompleteInitialSyncPreservesPostSetPendingCapture(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + setCall := f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).After(setCall).Return(nil, errors.New("readback timeout")).Times(1) + live := buildJSONIntent(t, f.ds, "nr-live", 10, true, map[string]any{ + "system": map[string]any{"hashed-password": "LivePlainPw1!"}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-live", []*types.TransactionIntent{live}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-live): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-live"); err != nil { + t.Fatalf("TransactionConfirm(tx-live): %v", err) + } + + if err := f.ds.ApplyInitialSync(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, nil, nil); err != nil { + t.Fatalf("ApplyInitialSync: %v", err) + } + if got := f.ds.confirmedApplied.Lookup( + hashedPasswordPath(), + "nr-live", + &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: "LivePlainPw1!"}}, + ); got != nil { + t.Fatalf("ApplyInitialSync falsely locked optimistic cleartext into baseline: %v", got) + } + + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{"hashed-password": "$6$live$realhash"}, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(real sync): %v", err) + } + + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED { + t.Fatalf("unexpected NOT_APPLIED after real sync captured hash: %v", ev) + } + } +} + +func TestDatastore_MutateOnWrite_ExplicitDeleteOnUpdatedHighOwnerOverrulesPreviouslyApplied(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + ctx := context.Background() + + f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Return(nil, errors.New("offline")).Times(1) + + highInit := buildJSONIntent(t, f.ds, "high-owner", 5, false, map[string]any{ + "system": map[string]any{"hashed-password": "HighPw1!"}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-high-init", []*types.TransactionIntent{highInit}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-high-init): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-high-init"); err != nil { + t.Fatalf("TransactionConfirm(tx-high-init): %v", err) + } + + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, nil); err != nil { + t.Fatalf("ApplyToRunning(clear): %v", err) + } + f.ds.syncTreeMutex.Lock() + f.ds.syncedPaths = nil + f.ds.syncTreeMutex.Unlock() + + f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).Return(&sdcpb.SetDataResponse{}, nil).Times(1) + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Return(&sdcpb.GetDataResponse{ + Notification: []*sdcpb.Notification{{ + Update: []*sdcpb.Update{{ + Path: &sdcpb.Path{Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("extra", nil), + sdcpb.NewPathElem("token", nil), + }}, + Value: &sdcpb.TypedValue{Value: &sdcpb.TypedValue_StringVal{StringVal: "$6$tok$hash"}}, + }}, + }}, + }, nil).Times(1) + + highUpdated := buildJSONIntent(t, f.ds, "high-owner", 5, false, map[string]any{ + "extra": map[string]any{"token": "HighTok1!"}, + }) + highUpdated.AddExplicitDeletes([]*sdcpb.Path{hashedPasswordPath()}) + + lowPA := buildPreviouslyAppliedJSONIntent(t, f.ds, "low-pa", 50, true, map[string]any{ + "system": map[string]any{"hashed-password": "LowOverruledPw1!"}, + }) + + if _, err := f.ds.TransactionSet(ctx, "tx-explicit-del", []*types.TransactionIntent{highUpdated, lowPA}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-explicit-del): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-explicit-del"); err != nil { + t.Fatalf("TransactionConfirm(tx-explicit-del): %v", err) + } + + for _, epoch := range f.ds.confirmedApplied.CausalCaptures() { + if newCanonicalLeafPath(epoch.path) == newCanonicalLeafPath(hashedPasswordPath()) && epoch.owner == "low-pa" { + t.Fatalf("overruled low-pa must not arm initial-sync seed under explicit delete by high-owner: %+v", epoch) + } + } +} + +func TestDatastore_MutateOnWrite_KeylessListSyncPathAndRollbackPreservation(t *testing.T) { + ctx := context.Background() + + t.Run("keyless intermediate list sync path clears absent awaitingInitialSyncSeed and records syncedPaths", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + f.sbi.EXPECT().Get(gomock.Any(), gomock.Any()).Times(0) + expectEmptySet(t, f.sbi) + + pa := buildPreviouslyAppliedJSONIntent(t, f.ds, "nr-list-pa", 10, true, map[string]any{ + "system": map[string]any{ + "user": []any{ + map[string]any{"username": "alice", "secret": "AlicePlain123"}, + }, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-pa-1", []*types.TransactionIntent{pa}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-pa-1): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-pa-1"); err != nil { + t.Fatalf("TransactionConfirm(tx-pa-1): %v", err) + } + + // Initial sync configured on keyless list leaf path /system/user/secret finds target empty. + keylessSecretSyncPath := &sdcpb.Path{Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("user", nil), + sdcpb.NewPathElem("secret", nil), + }} + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{keylessSecretSyncPath}, nil); err != nil { + t.Fatalf("ApplyToRunning(empty keyless list sync): %v", err) + } + + // Replaying PreviouslyApplied after /system/user/secret synced must also see syncedPaths coverage + // and NOT re-arm awaitingInitialSyncSeed. + expectEmptySet(t, f.sbi) + paReplay := buildPreviouslyAppliedJSONIntent(t, f.ds, "nr-list-pa", 10, true, map[string]any{ + "system": map[string]any{ + "user": []any{ + map[string]any{"username": "alice", "secret": "AlicePlain123"}, + }, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-pa-2", []*types.TransactionIntent{paReplay}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-pa-2): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-pa-2"); err != nil { + t.Fatalf("TransactionConfirm(tx-pa-2): %v", err) + } + + // Subsequent out-of-band CLI edit adding alice's secret on target must raise NOT_APPLIED. + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{keylessSecretSyncPath}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "user": []any{ + map[string]any{"username": "alice", "secret": "$6$cli$alicehash"}, + }, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning(later CLI edit): %v", err) + } + + foundNotApplied := false + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && + ev.GetPath().ToXPath(false) == "/system/user[username=alice]/secret" { + foundNotApplied = true + } + } + if !foundNotApplied { + t.Fatal("expected NOT_APPLIED on /system/user[username=alice]/secret after keyless list sync confirmed it absent") + } + }) + + t.Run("canceling unconfirmed PreviouslyApplied transaction restores prior Non-revertive baseline and learnedPaths", func(t *testing.T) { + ctrl := gomock.NewController(t) + f := newMOWDatastoreFixture(t, ctrl) + + if err := f.ds.ApplyToRunning(ctx, time.Now().UnixNano(), []*sdcpb.Path{{}}, + jsonImporter.NewJsonTreeImporter(map[string]any{ + "system": map[string]any{ + "fallback-auth": "$6$fallback$seeded", + "user": []any{ + map[string]any{"username": "alice", "secret": "$6$alice$unconfirmed"}, + }, + }, + }, consts.RunningIntentName, consts.RunningValuesPrio, false)); err != nil { + t.Fatalf("ApplyToRunning: %v", err) + } + + expectEmptySet(t, f.sbi) + lowNR := buildPreviouslyAppliedJSONIntent(t, f.ds, "low-nr", 20, true, map[string]any{ + "system": map[string]any{"fallback-auth": "LowFallback1!"}, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-low", []*types.TransactionIntent{lowNR}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-low): %v", err) + } + if err := f.ds.TransactionConfirm(ctx, "tx-low"); err != nil { + t.Fatalf("TransactionConfirm(tx-low): %v", err) + } + + assertFallbackUntouched := func(setCtx context.Context, source targettypes.TargetSource) (*sdcpb.SetDataResponse, error) { + upds, err := source.ToProtoUpdates(setCtx, true) + if err != nil { + return nil, err + } + for _, u := range upds { + if u.GetPath().ToXPath(false) == "/system/fallback-auth" { + t.Fatalf("unexpected southbound update on /system/fallback-auth: %v", u) + } + } + return &sdcpb.SetDataResponse{}, nil + } + f.sbi.EXPECT().Set(gomock.Any(), gomock.Any()).DoAndReturn(assertFallbackUntouched).Times(2) + + highPA := buildPreviouslyAppliedJSONIntent(t, f.ds, "high-pa", 5, true, map[string]any{ + "system": map[string]any{ + "primary-auth": "HighPrimaryPw!", + "user": []any{ + map[string]any{"username": "alice", "secret": "AliceCancelPw!"}, + }, + }, + }) + if _, err := f.ds.TransactionSet(ctx, "tx-cancel-pa", []*types.TransactionIntent{highPA}, nil, time.Minute, false); err != nil { + t.Fatalf("TransactionSet(tx-cancel-pa): %v", err) + } + if err := f.ds.TransactionCancel(ctx, "tx-cancel-pa"); err != nil { + t.Fatalf("TransactionCancel(tx-cancel-pa): %v", err) + } + + aliceSecretPath := &sdcpb.Path{Elem: []*sdcpb.PathElem{ + sdcpb.NewPathElem("system", nil), + sdcpb.NewPathElem("user", map[string]string{"username": "alice"}), + sdcpb.NewPathElem("secret", nil), + }} + if f.ds.confirmedApplied.IsLearnedMutateOnWritePath(aliceSecretPath) { + t.Fatal("canceled PreviouslyApplied transaction must not leak learned mutate-on-write paths") + } + + for _, ev := range collectWatchDeviationsBatch(t, f.ds) { + if ev.GetEvent() == sdcpb.DeviationEvent_UPDATE && + ev.GetReason() == sdcpb.DeviationReason_NOT_APPLIED && + ev.GetPath().ToXPath(false) == "/system/fallback-auth" { + t.Fatalf("canceled PreviouslyApplied transaction lost low-nr fallback-auth baseline: %v", ev) + } + } + }) +} + + + + + + + diff --git a/pkg/datastore/sync.go b/pkg/datastore/sync.go index c5b7b3b4..32119168 100644 --- a/pkg/datastore/sync.go +++ b/pkg/datastore/sync.go @@ -22,9 +22,24 @@ import ( // ApplyToRunning commits one sync observation. syncStartedAt is Unix // nanoseconds captured before the producer starts reading the target snapshot. func (d *Datastore) ApplyToRunning(ctx context.Context, syncStartedAt int64, deletes []*sdcpb.Path, importer importer.ImportConfigAdapter) error { + return d.applyToRunning(ctx, syncStartedAt, nil, deletes, importer) +} + +// ApplyInitialSync commits an initial merge-only sync observation while +// atomically recording syncPaths coverage before releasing syncTreeMutex or +// running performRevert. +func (d *Datastore) ApplyInitialSync(ctx context.Context, syncStartedAt int64, syncPaths []*sdcpb.Path, deletes []*sdcpb.Path, importer importer.ImportConfigAdapter) error { + return d.applyToRunning(ctx, syncStartedAt, syncPaths, deletes, importer) +} + +func (d *Datastore) applyToRunning(ctx context.Context, syncStartedAt int64, initialSyncPaths []*sdcpb.Path, deletes []*sdcpb.Path, importer importer.ImportConfigAdapter) error { log := logger.FromContext(ctx) + if err := d.ensureColdStartCandidatesLoaded(ctx); err != nil { + return err + } + d.syncTreeMutex.Lock() syncTreeUnlock := sync.OnceFunc(d.syncTreeMutex.Unlock) @@ -94,6 +109,11 @@ func (d *Datastore) ApplyToRunning(ctx context.Context, syncStartedAt int64, del if err := d.reconcilePendingCaptures(ctx, syncStartedAt, deletes, importedPaths); err != nil { return err } + if len(initialSyncPaths) > 0 { + d.reconcileInitialSyncSeedsLocked(initialSyncPaths) + d.recordSyncedPathsLocked(initialSyncPaths) + } + d.recordSyncedPathsLocked(deletes) // conditional trace logging if log := log.V(logger.VTrace); log.Enabled() { @@ -143,22 +163,19 @@ type pendingImportProbe struct { // beginPendingImportProbes prepares observation probes on d.syncTree for causal // pending paths not already covered by syncPaths; callers must hold syncTreeMutex. -func (d *Datastore) beginPendingImportProbes(ctx context.Context, syncStartedAt int64, syncPaths []*sdcpb.Path) []pendingImportProbe { +func (d *Datastore) beginPendingImportProbes(_ context.Context, syncStartedAt int64, syncPaths []*sdcpb.Path) []pendingImportProbe { var probes []pendingImportProbe for _, pending := range d.confirmedApplied.CausalCaptures() { - if !pending.IsPending() || syncStartedAt < pending.captureAfterNano || pathCoveredBySync(pending.path, syncPaths) { + if !pending.IsPending() || pending.BlocksSync(syncStartedAt) || pathCoveredBySync(pending.path, syncPaths) { continue } var running *api.LeafEntry - entry, err := ops.NavigateSdcpbPath(ctx, d.syncTree.Entry, pending.path) - if err == nil && entry != nil { - if r := entry.GetLeafVariants().GetByOwner(consts.RunningIntentName); r != nil { - if r.GetDeleteFlag() { - continue - } - r.MarkDelete(false) - running = r + if r := d.runningLeafEntryLocked(pending.path); r != nil { + if r.GetDeleteFlag() { + continue } + r.MarkDelete(false) + running = r } probes = append(probes, pendingImportProbe{ key: newCanonicalLeafPath(pending.path), @@ -171,7 +188,8 @@ func (d *Datastore) beginPendingImportProbes(ctx context.Context, syncStartedAt // finishPendingImportProbes restores temporary probe markers on untouched Running // leaves and returns the canonical paths observed during ImportConfig. -func (d *Datastore) finishPendingImportProbes(ctx context.Context, probes []pendingImportProbe) map[canonicalLeafPath]bool { +// Callers must hold syncTreeMutex. +func (d *Datastore) finishPendingImportProbes(_ context.Context, probes []pendingImportProbe) map[canonicalLeafPath]bool { if len(probes) == 0 { return nil } @@ -185,17 +203,38 @@ func (d *Datastore) finishPendingImportProbes(ctx context.Context, probes []pend } continue } - entry, err := ops.NavigateSdcpbPath(ctx, d.syncTree.Entry, probe.path) - if err == nil && entry != nil && entry.GetLeafVariants().GetByOwner(consts.RunningIntentName) != nil { + if d.runningLeafEntryLocked(probe.path) != nil { observed[probe.key] = true } } return observed } +func (d *Datastore) runningLeafEntryLocked(path *sdcpb.Path) *api.LeafEntry { + if d.syncTree == nil || d.syncTree.Entry == nil { + return nil + } + entry := ops.NavigateChildMap(d.syncTree.Entry, canonicalPath(path)) + if entry == nil { + return nil + } + return entry.GetLeafVariants().GetByOwner(consts.RunningIntentName) +} + +// reconcileInitialSyncSeedsLocked resolves deferred initial-sync baselines on +// syncPaths against d.syncTree. Callers must hold syncTreeMutex. +func (d *Datastore) reconcileInitialSyncSeedsLocked(syncPaths []*sdcpb.Path) { + for _, pending := range d.confirmedApplied.CausalCaptures() { + if !pending.IsAwaitingInitialSync() || !pathCoveredBySync(pending.path, syncPaths) { + continue + } + d.confirmedApplied.CompletePending(pending, d.runningValueLocked(pending.path)) + } +} + func (d *Datastore) reconcilePendingCaptures(ctx context.Context, syncStartedAt int64, syncPaths []*sdcpb.Path, importedPaths map[canonicalLeafPath]bool) error { for _, pending := range d.confirmedApplied.CausalCaptures() { - if syncStartedAt < pending.captureAfterNano { + if pending.BlocksSync(syncStartedAt) { restoreValue := pending.intendedValue if pending.confirmedValue != nil { restoreValue = pending.confirmedValue @@ -218,30 +257,50 @@ func (d *Datastore) reconcilePendingCaptures(ctx context.Context, syncStartedAt if !wasObserved { continue } - var observed *sdcpb.TypedValue - entry, err := ops.NavigateSdcpbPath(ctx, d.syncTree.Entry, pending.path) - if err == nil && entry != nil { - if running := entry.GetLeafVariants().GetByOwner(consts.RunningIntentName); running != nil { - observed = running.Value() - } - } else if err != nil && !errors.Is(err, ops.ErrNavigateSdcpbPathNotFound) { - return err - } + observed := d.runningValueLocked(pending.path) d.confirmedApplied.CompletePending(pending, observed) } return nil } +// recordSyncedPathsLocked appends canonical syncPaths not yet covered by +// d.syncedPaths. Callers must hold syncTreeMutex for writing. +func (d *Datastore) recordSyncedPathsLocked(syncPaths []*sdcpb.Path) { + for _, p := range syncPaths { + if !pathCoveredBySync(p, d.syncedPaths) { + d.syncedPaths = append(d.syncedPaths, canonicalPath(p)) + } + } +} + func pathCoveredBySync(path *sdcpb.Path, syncPaths []*sdcpb.Path) bool { - path = canonicalPath(path) + targetElems := canonicalPath(path).GetElem() for _, syncPath := range syncPaths { - if canonicalPath(syncPath).IsParentPathOf(path) { + if syncElemsCoverTarget(canonicalPath(syncPath).GetElem(), targetElems) { return true } } return false } +func syncElemsCoverTarget(syncElems, targetElems []*sdcpb.PathElem) bool { + if len(syncElems) > len(targetElems) { + return false + } + for i, se := range syncElems { + te := targetElems[i] + if se.GetName() != te.GetName() { + return false + } + for k, sv := range se.GetKey() { + if tv, ok := te.GetKey()[k]; !ok || tv != sv { + return false + } + } + } + return true +} + func (d *Datastore) NewEmptyTree(ctx context.Context) (*tree.RootEntry, error) { tc := d.newTreeContext() newTree, err := tree.NewTreeRoot(ctx, tc) diff --git a/pkg/datastore/target/gnmi/get.go b/pkg/datastore/target/gnmi/get.go index 74e8f67a..dac5c6ef 100644 --- a/pkg/datastore/target/gnmi/get.go +++ b/pkg/datastore/target/gnmi/get.go @@ -2,6 +2,7 @@ package gnmi import ( "context" + "errors" "sync" "time" @@ -146,6 +147,12 @@ func (s *GetSync) internalGetSync(req *sdcpb.GetDataRequest) { result, err := ops.TreeExport(s.syncTree.Entry, consts.RunningIntentName, consts.RunningValuesPrio, false) if err != nil { + if errors.Is(err, ops.ErrorIntentNotPresent) { + if applyErr := s.runningStore.ApplyToRunning(s.ctx, syncStartedAt, s.paths, nil); applyErr != nil { + log.Error(applyErr, "failure clearing empty synctree paths in running") + } + return + } log.Error(err, "failure exporting synctree") return } diff --git a/pkg/datastore/target/gnmi/stream.go b/pkg/datastore/target/gnmi/stream.go index f2818083..5f5b24bb 100644 --- a/pkg/datastore/target/gnmi/stream.go +++ b/pkg/datastore/target/gnmi/stream.go @@ -195,7 +195,7 @@ func (s *StreamSync) buildTreeSyncWithDatastore(cUS <-chan *NotificationData, in // commit hands the accumulated syncTree to a background goroutine and // continues with a fresh tree. It reports false when no fresh tree could // be created. - commit := func(replacePaths []*sdcpb.Path) bool { + commit := func(replacePaths []*sdcpb.Path, initialSyncPaths []*sdcpb.Path) bool { treeToCommit := syncTree syncStartedAt := batchStartedAt if syncStartedAt == 0 { @@ -217,7 +217,7 @@ func (s *StreamSync) buildTreeSyncWithDatastore(cUS <-chan *NotificationData, in defer close(done) defer inflight.Add(-1) <-waitFor - if err := s.syncToRunning(treeToCommit, syncStartedAt, replacePaths, true); err != nil { + if err := s.syncToRunning(treeToCommit, syncStartedAt, replacePaths, initialSyncPaths, true); err != nil { log.Error(err, "failed committing synctree to running") } }() @@ -254,10 +254,15 @@ func (s *StreamSync) buildTreeSyncWithDatastore(cUS <-chan *NotificationData, in replacePaths = s.paths awaitingFullSync = false } - if !commit(replacePaths) { + isInitialSync := tickerChan == nil + var initialSyncPaths []*sdcpb.Path + if isInitialSync { + initialSyncPaths = s.paths + } + if !commit(replacePaths, initialSyncPaths) { return } - if tickerChan == nil { + if isInitialSync { t := time.NewTicker(5 * time.Second) defer t.Stop() tickerChan = t.C @@ -280,7 +285,7 @@ func (s *StreamSync) buildTreeSyncWithDatastore(cUS <-chan *NotificationData, in continue } log.Info("SyncRunning due to ticker") - if !commit(nil) { + if !commit(nil, nil) { return } } @@ -369,7 +374,7 @@ func (s *StreamSync) gnmiSubscribe(subReq *gnmi.SubscribeRequest, updChan chan<- // // replacePaths are deleted from Running before the import, so Running under // those paths ends up equal to syncTree. An empty syncTree still applies them. -func (s *StreamSync) syncToRunning(syncTree *tree.RootEntry, syncStartedAt int64, replacePaths []*sdcpb.Path, logCount bool) error { +func (s *StreamSync) syncToRunning(syncTree *tree.RootEntry, syncStartedAt int64, replacePaths []*sdcpb.Path, initialSyncPaths []*sdcpb.Path, logCount bool) error { log := logger.FromContext(s.ctx) startTime := time.Now() @@ -377,6 +382,11 @@ func (s *StreamSync) syncToRunning(syncTree *tree.RootEntry, syncStartedAt int64 log.V(logger.VTrace).Info("exported tree", "tree", result.String()) if err != nil { if errors.Is(err, ops.ErrorIntentNotPresent) { + if len(initialSyncPaths) > 0 { + if initialStore, ok := s.runningStore.(types.InitialSyncStore); ok { + return initialStore.ApplyInitialSync(s.ctx, syncStartedAt, initialSyncPaths, replacePaths, nil) + } + } if len(replacePaths) == 0 { log.Info("sync no config changes") return nil @@ -398,7 +408,16 @@ func (s *StreamSync) syncToRunning(syncTree *tree.RootEntry, syncStartedAt int64 log.V(logger.VTrace).Info("synctree export done", "duration", time.Since(startTime).String()) startTime = time.Now() - err = s.runningStore.ApplyToRunning(s.ctx, syncStartedAt, deletes, proto.NewProtoTreeImporter(result)) + imp := proto.NewProtoTreeImporter(result) + if len(initialSyncPaths) > 0 { + if initialStore, ok := s.runningStore.(types.InitialSyncStore); ok { + err = initialStore.ApplyInitialSync(s.ctx, syncStartedAt, initialSyncPaths, deletes, imp) + } else { + err = s.runningStore.ApplyToRunning(s.ctx, syncStartedAt, deletes, imp) + } + } else { + err = s.runningStore.ApplyToRunning(s.ctx, syncStartedAt, deletes, imp) + } if err != nil { log.Error(err, "failed importing sync to running") return err diff --git a/pkg/datastore/target/gnmi/stream_test.go b/pkg/datastore/target/gnmi/stream_test.go index 934a5010..ce1f768d 100644 --- a/pkg/datastore/target/gnmi/stream_test.go +++ b/pkg/datastore/target/gnmi/stream_test.go @@ -32,10 +32,12 @@ type fakeRunningStore struct { calls atomic.Int32 - mu sync.Mutex - deletesSeen [][]*sdcpb.Path - importSeen []bool - startedSeen []int64 + mu sync.Mutex + deletesSeen [][]*sdcpb.Path + importSeen []bool + startedSeen []int64 + initialSyncPaths [][]*sdcpb.Path + initialSyncCalls atomic.Int32 } // applied returns a snapshot of the deletes and importer-presence of every completed ApplyToRunning call. @@ -77,6 +79,17 @@ func (f *fakeRunningStore) NewEmptyTree(ctx context.Context) (*tree.RootEntry, e return tree.NewTreeRoot(ctx, tc) } +func (f *fakeRunningStore) ApplyInitialSync(ctx context.Context, syncStartedAt int64, syncPaths []*sdcpb.Path, deletes []*sdcpb.Path, imp treeimporter.ImportConfigAdapter) error { + f.mu.Lock() + f.initialSyncPaths = append(f.initialSyncPaths, syncPaths) + f.mu.Unlock() + f.initialSyncCalls.Add(1) + if imp == nil && len(deletes) == 0 { + return nil + } + return f.ApplyToRunning(ctx, syncStartedAt, deletes, imp) +} + // fakeSyncTarget implements SyncTarget with channels the test controls. type fakeSyncTarget struct { respChan chan *gnmi.SubscribeResponse @@ -475,3 +488,53 @@ func TestStreamSync_ResubscribeReplacesSyncedPaths(t *testing.T) { } } } + +func TestStreamSyncAndGetSync_EmptyTargetMarksInitialSyncComplete(t *testing.T) { + t.Run("StreamSync initial SyncResponse on empty target notifies ApplyInitialSync", func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + _, target, store := newStreamSyncForTest(t, ctx, []string{"/interface"}) + target.respChan <- syncRespMsg() + + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) && store.initialSyncCalls.Load() < 1 { + time.Sleep(10 * time.Millisecond) + } + if got := store.initialSyncCalls.Load(); got != 1 { + t.Fatalf("ApplyInitialSync calls = %d, want 1", got) + } + store.mu.Lock() + defer store.mu.Unlock() + if len(store.initialSyncPaths[0]) != 1 || store.initialSyncPaths[0][0].ToXPath(false) != "/interface" { + t.Fatalf("ApplyInitialSync paths = %v, want [/interface]", store.initialSyncPaths[0]) + } + }) + + t.Run("GetSync on empty target applies paths with nil importer", func(t *testing.T) { + ctx := context.Background() + sc, schemaConf, err := testhelper.InitSDCIOSchema() + if err != nil { + t.Fatalf("init schema: %v", err) + } + scb := schemaClientPkg.NewSchemaClientBound(schemaConf, sc) + sharedPool := pool.NewSharedTaskPool(ctx, runtime.GOMAXPROCS(0)) + store := newFakeRunningStore(scb, sharedPool) + close(store.firstUnblock) + + syncer, err := NewGetSync(ctx, &fakeGetTarget{response: &sdcpb.GetDataResponse{}}, &config.SyncProtocol{ + Name: "get-empty", + Paths: []string{"/interface"}, + }, store, scb) + if err != nil { + t.Fatalf("NewGetSync: %v", err) + } + + syncer.internalGetSync(&sdcpb.GetDataRequest{}) + deletes, imported, _ := store.applied() + if len(deletes) != 1 || len(deletes[0]) != 1 || deletes[0][0].ToXPath(false) != "/interface" || imported[0] { + t.Fatalf("empty GetSync applied deletes=%v imported=%v, want ([/interface], false)", deletes, imported) + } + }) +} + diff --git a/pkg/datastore/target/types/runningstore.go b/pkg/datastore/target/types/runningstore.go index 02c33452..16fa152f 100644 --- a/pkg/datastore/target/types/runningstore.go +++ b/pkg/datastore/target/types/runningstore.go @@ -14,3 +14,10 @@ type RunningStore interface { ApplyToRunning(ctx context.Context, syncStartedAt int64, deletes []*sdcpb.Path, importer importer.ImportConfigAdapter) error NewEmptyTree(ctx context.Context) (*tree.RootEntry, error) } + +// InitialSyncStore is optionally implemented by a RunningStore that atomically +// records configured syncPaths coverage alongside an initial merge-only sync +// (such as the first StreamSync SyncResponse), even when importer is nil. +type InitialSyncStore interface { + ApplyInitialSync(ctx context.Context, syncStartedAt int64, syncPaths []*sdcpb.Path, deletes []*sdcpb.Path, importer importer.ImportConfigAdapter) error +} diff --git a/pkg/datastore/transaction_rpc.go b/pkg/datastore/transaction_rpc.go index 99e89b7b..4b4c4aa9 100644 --- a/pkg/datastore/transaction_rpc.go +++ b/pkg/datastore/transaction_rpc.go @@ -83,6 +83,12 @@ func (d *Datastore) replaceIntent(ctx context.Context, transaction *types.Transa log := logger.FromContext(ctx).WithValues("transaction-type", "replace") ctx = logger.IntoContext(ctx, log) + if !dryRun { + if err := d.ensureColdStartCandidatesLoaded(ctx); err != nil { + return nil, err + } + } + // create a new TreeContext tc := d.newTreeContext() @@ -195,6 +201,11 @@ func (d *Datastore) LoadAllButRunningIntents(ctx context.Context, root *tree.Roo // lowlevelTransactionSet func (d *Datastore) lowlevelTransactionSet(ctx context.Context, transaction *types.Transaction, dryRun bool) (*sdcpb.TransactionSetResponse, error) { log := logger.FromContext(ctx) + if !dryRun { + if err := d.ensureColdStartCandidatesLoaded(ctx); err != nil { + return nil, err + } + } d.syncTreeMutex.RLock() root, err := d.syncTree.DeepCopy(ctx) d.syncTreeMutex.RUnlock() @@ -279,8 +290,11 @@ func (d *Datastore) lowlevelTransactionSet(ctx context.Context, transaction *typ log.V(logger.VTrace).Info("populated tree", "tree", root.String()) + restoreValidationOverlay := d.attachValidationCryptOverlay(root, transaction.GetNewIntents()) + // perform validation validationResult, validationStats := validation.Validate(ctx, root.Entry, d.config.Validation, d.taskPool) + restoreValidationOverlay() log.V(logger.VDebug).Info("transaction validation stats", "transaction-id", transaction.GetTransactionId(), "stats", validationStats.String()) @@ -382,10 +396,19 @@ func (d *Datastore) lowlevelTransactionSet(ctx context.Context, transaction *typ } } + if !transaction.IsRollback() { + d.capturePreTransactionBaselines(updates, deletes) + } err = d.applyReadbacksAndWriteBackRunning(ctx, updates, deletes, readbacks, setDoneUnixNano) if err != nil { return nil, err } + d.evictStaleBaselines(ctx, root) + if transaction.IsRollback() { + d.restoreRolledBackBaselines(ctx, root, updates, deletes) + } else { + d.seedPreviouslyAppliedBaselines(root, transaction.GetNewIntents(), updates) + } log.Info("transaction completed") diff --git a/pkg/tree/api/leaf_variants.go b/pkg/tree/api/leaf_variants.go index a9db5acd..1e79a019 100644 --- a/pkg/tree/api/leaf_variants.go +++ b/pkg/tree/api/leaf_variants.go @@ -376,6 +376,29 @@ func (lv *LeafVariants) GetHighestPrecedence(onlyNewOrUpdated bool, includeDefau return nil } +// ActiveIntendedWinner returns the highest-precedence active intended variant, +// or nil when no intended variant exists or an explicit delete wins. +func (lv *LeafVariants) ActiveIntendedWinner() *LeafEntry { + if lv == nil { + return nil + } + lv.lesMutex.RLock() + defer lv.lesMutex.RUnlock() + var highest *LeafEntry + for _, le := range lv.les { + if le.Owner() == treeconsts.DefaultsIntentName || le.Owner() == treeconsts.RunningIntentName || FilterDeletedNotExplicitDelete(le) { + continue + } + if highest == nil || le.Priority() < highest.Priority() { + highest = le + } + } + if highest == nil || highest.GetExplicitDeleteFlag() { + return nil + } + return highest +} + // DriftBaseline returns the confirmed applied value for highest when registered // for this leaf's path, owner, and intended value, falling back to highest.Value(). func (lv *LeafVariants) DriftBaseline(highest *LeafEntry) *sdcpb.TypedValue { diff --git a/pkg/tree/api/tree_context.go b/pkg/tree/api/tree_context.go index c36776b7..4f685992 100644 --- a/pkg/tree/api/tree_context.go +++ b/pkg/tree/api/tree_context.go @@ -29,6 +29,8 @@ type TreeContext interface { ConfirmedAppliedValue(path *sdcpb.Path, owner string, intendedValue *sdcpb.TypedValue) *sdcpb.TypedValue // IsLearnedMutateOnWritePath reports whether path's keyless schema path was dynamically learned as mutate-on-write. IsLearnedMutateOnWritePath(path *sdcpb.Path) bool + // SetLearnedMutateOnWritePaths replaces the dynamic mutate-on-write path lookup used for this tree context. + SetLearnedMutateOnWritePaths(learned LearnedMutateOnWritePathSet) } // IsMutateOnWriteEntry reports whether e is classified as a mutate-on-write diff --git a/pkg/tree/ops/navigatesdcpbpath.go b/pkg/tree/ops/navigatesdcpbpath.go index 2e0a8bfc..c4be9a2c 100644 --- a/pkg/tree/ops/navigatesdcpbpath.go +++ b/pkg/tree/ops/navigatesdcpbpath.go @@ -65,3 +65,30 @@ func NavigateSdcpbPath(ctx context.Context, e api.Entry, path *sdcpb.Path) (api. return NavigateSdcpbPath(ctx, child, path.CopyAndRemoveFirstPathElem()) } } + +// NavigateChildMap resolves path directly through Entry child maps without +// consulting YANG choice active-case filtering, returning nil if any segment is absent. +func NavigateChildMap(e api.Entry, path *sdcpb.Path) api.Entry { + if e == nil || path == nil { + return nil + } + curr := e + if path.IsRootBased { + curr = GetRoot(e) + } + for _, pe := range path.GetElem() { + next, ok := curr.GetChildMap().GetEntry(pe.GetName()) + if !ok { + return nil + } + curr = next + for keyVal := range pe.PathElemNamesKeysOnly() { + keyChild, ok := curr.GetChildMap().GetEntry(keyVal) + if !ok { + return nil + } + curr = keyChild + } + } + return curr +} diff --git a/pkg/tree/tree_context.go b/pkg/tree/tree_context.go index aa00a9fb..5e513fce 100644 --- a/pkg/tree/tree_context.go +++ b/pkg/tree/tree_context.go @@ -90,3 +90,9 @@ func (t *TreeContext) IsLearnedMutateOnWritePath(path *sdcpb.Path) bool { } return t.learnedMutateOnWritePaths.IsLearnedMutateOnWritePath(path) } + +func (t *TreeContext) SetLearnedMutateOnWritePaths(learned api.LearnedMutateOnWritePathSet) { + if t != nil { + t.learnedMutateOnWritePaths = learned + } +} From 528d8a947c52a3dc10e1be1495efb9304432ac42 Mon Sep 17 00:00:00 2001 From: Markus Vahlenkamp Date: Thu, 26 Nov 2026 11:37:14 +0100 Subject: [PATCH 7/7] build(go): pin sdc-protos and schema-server to pushed commits Drop the local ../sdc-protos and ../schema-server replaces so the module builds from a clean clone. Require sdc-protos at fe084f2516a8 and schema-server at 1476e1424a8b, the draft branch commits in sdcio/sdc-protos#144 and sdcio/schema-server#264. Signed-off-by: Markus Vahlenkamp --- go.mod | 9 ++------- go.sum | 4 ++++ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/go.mod b/go.mod index b387ce3e..b634e3b7 100644 --- a/go.mod +++ b/go.mod @@ -4,11 +4,6 @@ go 1.26.0 replace github.com/openconfig/goyang v1.6.3 => github.com/sdcio/goyang v1.6.2-2 -replace ( - github.com/sdcio/schema-server => ../schema-server - github.com/sdcio/sdc-protos => ../sdc-protos -) - require ( github.com/AlekSi/pointer v1.2.0 github.com/beevik/etree v1.8.1 @@ -28,8 +23,8 @@ require ( github.com/scrapli/scrapligo v1.4.4 github.com/sdcio/cache v0.0.39 github.com/sdcio/logger v0.0.3 - github.com/sdcio/schema-server v0.0.34 - github.com/sdcio/sdc-protos v0.0.56 + github.com/sdcio/schema-server v0.0.35-0.20261126103548-1476e1424a8b + github.com/sdcio/sdc-protos v0.0.57-0.20261120130348-fe084f2516a8 github.com/sdcio/yang-parser v0.0.12 github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.1.0 diff --git a/go.sum b/go.sum index 84bf726d..977bd00f 100644 --- a/go.sum +++ b/go.sum @@ -189,6 +189,10 @@ github.com/sdcio/goyang v1.6.2-2 h1:qfeUKBmoKpiKAruuEc3+V8wgHKP/n1jRDEnTy23knV8= github.com/sdcio/goyang v1.6.2-2/go.mod h1:5WolITjek1NF8yrNERyVZ7jqjOClJTpO8p/+OwmETM4= github.com/sdcio/logger v0.0.3 h1:IFUbObObGry+S8lHGwOQKKRxJSuOphgRU/hxVhOdMOM= github.com/sdcio/logger v0.0.3/go.mod h1:yWaOxK/G6vszjg8tKZiMqiEjlZouHsjFME4zSk+SAEA= +github.com/sdcio/schema-server v0.0.35-0.20261126103548-1476e1424a8b h1:H+jGv8QV/RMpTFveiJga1C4MuM3yhQkkyFS374XgA7o= +github.com/sdcio/schema-server v0.0.35-0.20261126103548-1476e1424a8b/go.mod h1:aU4iDCAuza0oLC9Fx+oADKnDg7aQYcJvPDz/U9Dwd9k= +github.com/sdcio/sdc-protos v0.0.57-0.20261120130348-fe084f2516a8 h1:bpRX03TyJp4FMCin8zy1luh69jmt4axHxSUXbpj1GGE= +github.com/sdcio/sdc-protos v0.0.57-0.20261120130348-fe084f2516a8/go.mod h1:hER0riYU3G55NnMQ0p0R9kIL/fzqq1zab4pOgUT3Yfg= github.com/sdcio/yang-parser v0.0.12 h1:RSSeqfAOIsJx5Lno5u4/ezyOmQYUduQ22rBfU/mtpJ4= github.com/sdcio/yang-parser v0.0.12/go.mod h1:CBqn3Miq85qmFVGHxHXHLluXkaIOsTzV06IM4DW6+D4= github.com/sirikothe/gotextfsm v1.0.1-0.20200816110946-6aa2cfd355e4 h1:FHUL2HofYJuslFOQdy/JjjP36zxqIpd/dcoiwLMIs7k=