Files
configkit/internal/engine/history_source.go

288 lines
10 KiB
Go

package engine
import "go.maximumdirect.net/configkit/internal/document"
type historyPathOrigin struct {
path Path
origin Origin
sensitive bool
}
type historySourcePayloadKind uint8
const (
historySourceApplicationPayload historySourcePayloadKind = iota
historySourceOverlayPayload
historySourceSummaryPayload
)
// historySourcePayload keeps source values and replacement facts under the
// shared model's ownership. Application documents remain shared when immutable.
type historySourcePayload struct {
kind historySourcePayloadKind
application historyApplication
overlay overlayRecord
applicationRef historyPayloadRef
hasApplicationRef bool
path Path
origin Origin
}
func (builder *historyBuilder) observeBaseline(root *document.Node) {
builder.requireOpen()
if root == nil {
return
}
builder.model.baseline = root
payload := builder.nextPayload(historyPhaseBaseline)
defaultAttribution := builder.addAttribution(Origin{Layer: LayerDefault}, nil, nil)
walkDocument(root, Path{}, func(path Path, node *document.Node) {
builder.addObservation(historyObservation{
path: path, phase: historyPhaseBaseline, payload: payload,
reportedPath: path, role: historyRoleDefinition,
afterPresent: true, sensitive: node.Sensitive,
attributionRef: defaultAttribution,
})
})
}
// observeSourceEvidence registers raw source contributions, replacement sides,
// and the surviving structural definition summaries in producer order.
func (builder *historyBuilder) observeSourceEvidence(root *document.Node, origins map[string]Origin, applications []historyApplication, records []overlayRecord) {
builder.requireOpen()
if len(applications) == 0 && len(records) == 0 {
return
}
operations := newSourceOperationIndex(builder.model)
applicationsBySource := make(map[string]historyPayloadRef)
applicationsByLayer := make(map[Layer][]historyPayloadRef)
for index := range applications {
application := applications[index]
payload := builder.addSourcePayload(&application, nil)
applicationsByLayer[application.layer] = append(applicationsByLayer[application.layer], payload)
walkHistoryApplication(application, func(_, effective Path, node *document.Node) {
if node.Location.SourceID != "" {
applicationsBySource[node.Location.SourceID] = payload
}
origin := sourceApplicationOrigin(application, node)
for _, location := range origin.Locations {
if location.SourceID != "" {
applicationsBySource[location.SourceID] = payload
}
}
attribution := builder.addAttribution(origin, nil, nil)
builder.addObservation(historyObservation{
path: effective, phase: historyPhaseSources, payload: payload,
reportedPath: effective, role: historyRoleContribution,
afterPresent: true, sensitive: node.Sensitive,
attributionRef: attribution,
})
})
}
for index := range records {
record := records[index]
payload := builder.addSourcePayload(nil, &record)
applicationRef, hasApplication := sourceApplicationForRecord(record, applicationsBySource, applicationsByLayer)
if hasApplication {
owned := &builder.model.sourcePayloads[payload.id]
owned.applicationRef = applicationRef
owned.hasApplicationRef = true
}
for displacedIndex, displaced := range record.displaced {
if operations.contains(builder.model, displaced.path, displaced.origin) {
continue
}
definitionPayload := payload
definitionPayload.substep = displacedIndex + 1
definition := builder.addAttribution(displaced.origin, nil, nil)
builder.addObservation(historyObservation{
path: displaced.path, phase: historyPhaseSources, payload: definitionPayload,
reportedPath: displaced.path, role: historyRoleDefinition,
beforePresent: true,
attributionRef: definition,
})
}
attribution := builder.addAttribution(record.change.Origin, nil, nil)
for _, displaced := range record.displaced {
builder.addObservation(historyObservation{
path: displaced.path, phase: historyPhaseSources, payload: payload,
reportedPath: record.change.Path, role: historyRoleOperation,
beforePresent: true, attributionRef: attribution,
})
}
for _, introduced := range record.introduced {
id := builder.addObservation(historyObservation{
path: introduced.path, phase: historyPhaseSources, payload: payload,
reportedPath: record.change.Path, role: historyRoleOperation,
afterPresent: true, sensitive: introduced.sensitive,
attributionRef: attribution,
})
operations.add(builder.model, id)
}
}
if root == nil {
return
}
walkDocument(root, Path{}, func(path Path, node *document.Node) {
origin, found := origins[path.String()]
if !found || origin.Layer == "" || operations.contains(builder.model, path, origin) {
return
}
payload := builder.addSourceSummary(path, origin)
attribution := builder.addAttribution(origin, nil, nil)
builder.addObservation(historyObservation{
path: path, phase: historyPhaseSources, payload: payload,
reportedPath: path, role: historyRoleCompositeDefinition,
afterPresent: true, sensitive: node.Sensitive,
attributionRef: attribution,
})
})
}
func sourceApplicationForRecord(record overlayRecord, bySource map[string]historyPayloadRef, byLayer map[Layer][]historyPayloadRef) (historyPayloadRef, bool) {
for _, location := range record.change.Origin.Locations {
if reference, found := bySource[location.SourceID]; found && location.SourceID != "" {
return reference, true
}
}
applications := byLayer[record.change.Origin.Layer]
if len(applications) == 1 {
return applications[0], true
}
return historyPayloadRef{}, false
}
func (builder *historyBuilder) addSourcePayload(application *historyApplication, overlay *overlayRecord) historyPayloadRef {
payload := builder.nextPayload(historyPhaseSources)
if payload.id != len(builder.model.sourcePayloads) {
panic("configkit: source payload identifiers are out of order")
}
owned := historySourcePayload{}
switch {
case application != nil:
owned.kind = historySourceApplicationPayload
owned.application = cloneHistoryApplications([]historyApplication{*application})[0]
case overlay != nil:
owned.kind = historySourceOverlayPayload
owned.overlay = cloneOverlayRecords([]overlayRecord{*overlay})[0]
default:
panic("configkit: source payload requires a producer")
}
builder.model.sourcePayloads = append(builder.model.sourcePayloads, owned)
return payload
}
func (builder *historyBuilder) addSourceSummary(path Path, origin Origin) historyPayloadRef {
payload := builder.nextPayload(historyPhaseSources)
if payload.id != len(builder.model.sourcePayloads) {
panic("configkit: source payload identifiers are out of order")
}
builder.model.sourcePayloads = append(builder.model.sourcePayloads, historySourcePayload{
kind: historySourceSummaryPayload, path: path.clone(), origin: cloneOrigin(origin),
})
return payload
}
func sourceApplicationOrigin(application historyApplication, node *document.Node) Origin {
origin := cloneOrigin(application.origin)
origin.Layer = application.layer
if node.Location.SourceID != "" {
origin.Locations = []Location{publicLocation(node.Location)}
}
return origin
}
// sourceOperationIndex is local to source evidence construction. It indexes only
// completed after-operation facts, narrowing attribution checks by source ID.
// General observation lists also contain all contributions at a path and grow
// with every replacement; scanning those lists per replacement is quadratic.
type sourceOperationIndex struct {
byPath map[string][]int
bySource map[sourceOperationSource][]int
}
type sourceOperationSource struct {
pointer string
sourceID string
}
func newSourceOperationIndex(model *historyModel) *sourceOperationIndex {
index := &sourceOperationIndex{
byPath: make(map[string][]int),
bySource: make(map[sourceOperationSource][]int),
}
for id := range model.observations {
index.add(model, id)
}
return index
}
func (index *sourceOperationIndex) add(model *historyModel, id int) {
if id < 0 {
return
}
observation := model.observations[id]
if observation.phase != historyPhaseSources || observation.role != historyRoleOperation || !observation.afterPresent {
return
}
attribution, ok := model.resolveAttribution(observation.attributionRef)
if !ok {
return
}
pointer := observation.path.String()
index.byPath[pointer] = append(index.byPath[pointer], id)
seen := make(map[string]struct{}, len(attribution.origin.Locations))
for _, location := range attribution.origin.Locations {
if _, found := seen[location.SourceID]; found {
continue
}
seen[location.SourceID] = struct{}{}
key := sourceOperationSource{pointer: pointer, sourceID: location.SourceID}
index.bySource[key] = append(index.bySource[key], id)
}
}
func (index *sourceOperationIndex) contains(model *historyModel, path Path, origin Origin) bool {
pointer := path.String()
candidates := index.byPath[pointer]
if len(origin.Locations) != 0 {
// Every representing origin must include this source, for both exact and
// ancestor replacements. The full predicate still checks all locations,
// contributor traces, layers, operations and concrete path shapes.
candidates = index.bySource[sourceOperationSource{pointer: pointer, sourceID: origin.Locations[0].SourceID}]
}
for _, id := range candidates {
observation := model.observations[id]
if !sameConcreteHistoryPath(path, observation.path) {
continue
}
attribution, _ := model.resolveAttribution(observation.attributionRef)
if originRepresentedByChange(path, origin, Change{Path: observation.reportedPath, Origin: attribution.origin}) {
return true
}
}
return false
}
func originRepresentedByChange(path Path, origin Origin, change Change) bool {
if change.Path.String() == path.String() {
return originContainedBy(origin, change.Origin)
}
if !pathContains(change.Path, path) || origin.Layer != change.Origin.Layer || origin.Operation != change.Origin.Operation {
return false
}
// A subtree replacement records descendant contributions only when their
// source identities are present in the ancestor operation attribution.
recordedSources := make(map[string]struct{}, len(change.Origin.Locations))
for _, recorded := range change.Origin.Locations {
recordedSources[recorded.SourceID] = struct{}{}
}
for _, location := range origin.Locations {
if _, found := recordedSources[location.SourceID]; !found {
return false
}
}
return true
}