← Back to Pull requests

objectfs: wire streams change-log for metadata mutations #68

Merged
codebot-robot merged 10 files (1999 lines) on Sep 25, 2026 16:04 UTC
View on GitHub
codebot-robot codebot-robot commented on Sep 25, 2026 15:36 UTC
Author

This PR integrates the Streams WAL client into ObjectFS Volume and Server to transition ObjectFS metadata to a change-log database model.

Key changes:

  • Define MutationRecord and discrete mutation types (MKDIR, CREATE_FILE, WRITE_FILE, TRUNCATE_FILE, UNLINK, RMDIR, RENAME).

  • Wire Streams WAL logging to mutating operations in Volume with configurable durability levels (Local, Witness, Permanent) and WriteMode synchronization.

  • Implement ApplyRecordLocked and deterministic crash recovery replay from local WAL segment records on volume startup.

  • Add --wal-dir, --wal-target, and --wal-durability flags to objectfs-controller.

  • Add unit tests for Streams WAL change-logging, crash recovery replay, and durability modes.
  • Fixes #66

    Diff: 1999 lines (+1673 / -326) across 10 files Reviewer: justinsb Review duration: 28m
    All Vouch review confidence checks passed
    Residual risk 0.16 = Change Risk (0.56) × (1 − Review Confidence (0.71)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.56 · 1999 lines diff across 10 files
    0.56
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.83 · 5 substantive comment(s)
    0.83
    Model 3 · Review Timing & Attention
    Session adequacy: 56% · Reviewer familiarity: 35%
    70%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    9 items
    justinsb justinsb commented on code on Sep 25, 2026 15:41 UTC
    Code Review
    pkg/objectfs/controller/mutation.go:1
    @@ -0,0 +1,66 @@
    +/*
    +Copyright 2026 Google LLC
    +
    +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 controller
    +
    +import (
    +	"encoding/json"
    +	"fmt"
    +	"time"
    +)
    +
    +// MutationType identifies the kind of filesystem metadata mutation.
    +type MutationType string
    +
    +const (
    +	MutationMkdir        MutationType = "MKDIR"
    +	MutationCreateFile   MutationType = "CREATE_FILE"
    +	MutationWriteFile    MutationType = "WRITE_FILE"
    +	MutationTruncateFile MutationType = "TRUNCATE_FILE"
    +	MutationUnlink       MutationType = "UNLINK"
    +	MutationRmdir        MutationType = "RMDIR"
    +	MutationRename       MutationType = "RENAME"
    +)
    +
    +// MutationRecord represents a discrete metadata change-log record in the Streams WAL.

    Can we use a proto format here?

    justinsb justinsb commented on code on Sep 25, 2026 15:46 UTC
    Code Review
    pkg/objectfs/controller/volume.go:1
    @@ -117,6 +158,74 @@ func NewVolume(volumeID string, backend ObjectStorageBackend, broadcaster *Event
     	return v
     }
     
    +// VolumeID returns the volume identifier.
    +func (v *Volume) VolumeID() string {
    +	return v.volumeID
    +}
    +
    +// Stream returns the configured WAL stream, or nil.
    +func (v *Volume) Stream() walclient.Stream {
    +	v.mu.RLock()
    +	defer v.mu.RUnlock()
    +	return v.stream
    +}
    +
    +// StreamID returns the stream UUID associated with this volume.
    +func (v *Volume) StreamID() uuid.UUID {
    +	return v.streamID
    +}
    +
    +// Durability returns the default durability level configured on this volume.
    +func (v *Volume) Durability() walclient.Level {
    +	v.mu.RLock()
    +	defer v.mu.RUnlock()
    +	return v.durability
    +}
    +
    +// Close closes the volume and any underlying WAL streams.
    +func (v *Volume) Close() error {
    +	v.mu.Lock()
    +	defer v.mu.Unlock()
    +	if v.stream != nil {
    +		return v.stream.Close()
    +	}
    +	return nil
    +}
    +
    +func (v *Volume) logMutationLocked(ctx context.Context, record *MutationRecord, reqLevel *walclient.Level) error {
    +	if v.stream == nil {
    +		return nil
    +	}
    +	payload, err := record.Encode()
    +	if err != nil {
    +		return fmt.Errorf("failed to encode mutation record: %w", err)
    +	}
    +	seq, err := v.stream.Append(ctx, payload)
    +	if err != nil {
    +		return fmt.Errorf("failed to append mutation to WAL stream: %w", err)
    +	}
    +	record.StreamSeq = seq
    +
    +	durability := v.durability
    +	if reqLevel != nil {
    +		durability = *reqLevel
    +	}
    +
    +	switch durability {

    Let's add a TODO here, we normally will also want to write a blob and then wait for both.

    justinsb justinsb commented on code on Sep 25, 2026 15:46 UTC
    Code Review
    pkg/objectfs/controller/volume.go:1
    @@ -88,11 +91,44 @@ type Volume struct {
     	broadcaster  *EventBroadcaster
     	maxInlineLen int64
     
    +	stream     walclient.Stream
    +	durability walclient.Level
    +	streamID   uuid.UUID
    +
     	lastFlushedMetadata    *VolumeMetadata
     	deletedPathsSinceFlush []string
     }
     
    -func NewVolume(volumeID string, backend ObjectStorageBackend, broadcaster *EventBroadcaster) *Volume {
    +// VolumeOption configures a Volume instance.
    +type VolumeOption func(*Volume)
    +
    +// WithStream sets the WAL stream for metadata change-logging.
    +func WithStream(stream walclient.Stream) VolumeOption {
    +	return func(v *Volume) {
    +		v.stream = stream
    +	}
    +}
    +
    +// WithDurability sets the default durability level for metadata changes.
    +func WithDurability(level walclient.Level) VolumeOption {
    +	return func(v *Volume) {
    +		v.durability = level
    +	}
    +}
    +
    +// WithStreamID sets an explicit Stream UUID for this volume.
    +func WithStreamID(id uuid.UUID) VolumeOption {
    +	return func(v *Volume) {
    +		v.streamID = id
    +	}
    +}
    +
    +// StreamIDForVolume generates a deterministic UUID for a given volume ID.
    +func StreamIDForVolume(volumeID string) uuid.UUID {

    Let's add a TODO here: should volume IDs be UUIDs (probably yes)

    justinsb justinsb commented on code on Sep 25, 2026 15:47 UTC
    Code Review
    cmd/objectfs-controller/main.go:1
    @@ -68,8 +72,25 @@ func main() {
     		klog.Fatalf("failed to initialize backend %q: %v", *backendFlag, err)
     	}
     
    +	var serverOpts []controller.ServerOption
    +	if *walDir != "" {

    Let's add a todo: we always want to assume a WAL, and maybe it would be nice to have a wal-client mode that was local-only e.g. for testing.

    justinsb justinsb commented on code on Sep 25, 2026 15:49 UTC
    Code Review
    pkg/objectfs/controller/volume.go:1
    @@ -418,6 +556,22 @@ func (v *Volume) CreateFile(ctx context.Context, p string, mode uint32, initialC
     	parent.children[baseName] = child
     	parent.modTime = now
     
    +	rec := &MutationRecord{

    Let's add a TODO: orient everything around the structure of these operations, there is no need to translate back-and-forth. We probably could replace our whole protocol with a "DoOperation" method, which then keys on Type to validate etc.

    justinsb justinsb commented on code on Sep 25, 2026 15:51 UTC
    Code Review
    pkg/objectfs/controller/volume.go:1
    @@ -649,6 +842,15 @@ func (v *Volume) Unlink(ctx context.Context, p string) error {
     	parent.modTime = time.Now()
     	v.deletedPathsSinceFlush = append(v.deletedPathsSinceFlush, p)
     
    +	rec := &MutationRecord{
    +		Type:     MutationUnlink,
    +		VolumeID: v.volumeID,
    +		Path:     p,

    Although on the other hand we probably want to store items in the log more efficiently, e.g. we probably don't want the path, we want the parent dnode (?) and the name of the entry we are deleting here.

    I think FUSE works like this though, so not sure if this is a sign of us doing too many translations.

    justinsb justinsb commented on code on Sep 25, 2026 15:52 UTC
    Code Review
    pkg/objectfs/controller/volume.go:1
    @@ -1054,87 +1284,418 @@ func (v *Volume) loadFromErofsSnapshotLocked(reader *erofs.Reader, rawReader io.
     	return nil
     }
     
    -func (v *Volume) LoadFromBackend(ctx context.Context) error {
    -	v.mu.Lock()
    -	defer v.mu.Unlock()
    -
    -	if v.backend == nil {
    -		return nil
    +func (v *Volume) findOrCreateDirParentsLocked(p string) (*FSNode, error) {
    +	p = cleanPath(p)
    +	if p == "/" {
    +		return v.root, nil
     	}
    -
    -	// 1. Try loading from latest EROFS snapshot
    -	latestSnapshotName, err := v.findLatestSnapshotNameLocked(ctx)
    -	if err == nil && latestSnapshotName != "" {
    -		snapshotKey := path.Join("volumes", v.volumeID, "meta", latestSnapshotName)
    -		var imgBuf bytes.Buffer
    -		err := v.backend.GetObject(ctx, "", snapshotKey, 0, 0, &imgBuf)
    -		if err == nil && imgBuf.Len() > 0 {
    -			readerAt := bytes.NewReader(imgBuf.Bytes())
    -			reader, err := erofs.NewReader(readerAt)
    -			if err == nil {
    -				if err := v.loadFromErofsSnapshotLocked(reader, readerAt); err == nil {
    -					return nil
    -				}
    +	parts := strings.Split(strings.Trim(p, "/"), "/")
    +	curr := v.root
    +	currentPath := ""
    +	for _, part := range parts {
    +		currentPath = path.Join(currentPath, part)
    +		curr.mu.Lock()
    +		child, ok := curr.children[part]
    +		if !ok {
    +			child = &FSNode{
    +				inode:    v.allocInode(),
    +				name:     part,
    +				path:     "/" + currentPath,
    +				isDir:    true,
    +				mode:     0755 | syscall.S_IFDIR,
    +				modTime:  time.Now(),
    +				children: make(map[string]*FSNode),
    +				parent:   curr,
     			}
    +			curr.children[part] = child
     		}
    +		curr.mu.Unlock()
    +		curr = child
     	}
    +	return curr, nil
    +}
     
    -	// 2. Fallback to legacy JSON metadata file
    -	var metaBuf bytes.Buffer
    -	err = v.backend.GetObject(ctx, v.volumeID, MetadataFileName, 0, 0, &metaBuf)
    -	if err != nil || metaBuf.Len() == 0 {
    -		return nil
    +// ApplyRecordLocked applies a single mutation record to the in-memory filesystem tree.
    +func (v *Volume) ApplyRecordLocked(record *MutationRecord) error {
    +	if record.Inode >= v.nextInode {
    +		v.nextInode = record.Inode + 1
     	}
    +	switch record.Type {
    +	case MutationMkdir:
    +		p := cleanPath(record.Path)
    +		if p == "/" {
    +			return nil
    +		}
    +		parentPath := path.Dir(p)
    +		baseName := path.Base(p)
    +		parent, err := v.findOrCreateDirParentsLocked(parentPath)
    +		if err != nil {
    +			return err
    +		}
    +		mode := record.Mode
    +		if mode == 0 {
    +			mode = 0755
    +		}
    +		mode |= syscall.S_IFDIR
    +		inode := record.Inode
    +		if inode == 0 {
    +			inode = v.allocInode()
    +		}
    +		modTime := record.ModTime
    +		if modTime.IsZero() {
    +			modTime = time.Now()
    +		}
    +		parent.mu.Lock()
    +		defer parent.mu.Unlock()
    +		child, exists := parent.children[baseName]
    +		if !exists {
    +			child = &FSNode{
    +				inode:    inode,
    +				name:     baseName,
    +				path:     p,
    +				isDir:    true,
    +				mode:     mode,
    +				modTime:  modTime,
    +				children: make(map[string]*FSNode),
    +				parent:   parent,
    +			}
    +			parent.children[baseName] = child
    +		} else {
    +			child.mode = mode
    +			child.modTime = modTime
    +		}
    +		parent.modTime = modTime
    +		return nil
     
    -	var meta VolumeMetadata
    -	if err := json.Unmarshal(metaBuf.Bytes(), &meta); err != nil {
    -		return fmt.Errorf("failed to parse volume metadata: %w", err)
    -	}
    +	case MutationCreateFile:
    +		p := cleanPath(record.Path)
    +		if p == "/" {
    +			return fmt.Errorf("cannot create file at root: %w", syscall.EISDIR)
    +		}
    +		parentPath := path.Dir(p)
    +		baseName := path.Base(p)
    +		parent, err := v.findOrCreateDirParentsLocked(parentPath)
    +		if err != nil {
    +			return err
    +		}
    +		mode := record.Mode
    +		if mode == 0 {
    +			mode = 0644
    +		}
    +		mode |= syscall.S_IFREG
    +		inode := record.Inode
    +		if inode == 0 {
    +			inode = v.allocInode()
    +		}
    +		modTime := record.ModTime
    +		if modTime.IsZero() {
    +			modTime = time.Now()
    +		}
    +		var stream blob.ByteStream
    +		if len(record.Data) > 0 {
    +			stream = blob.NewByteStreamFromBytes(record.Data)
    +		}
    +		parent.mu.Lock()
    +		defer parent.mu.Unlock()
    +		child, exists := parent.children[baseName]
    +		if exists {
    +			child.mu.Lock()
    +			if child.data != nil {
    +				_ = child.data.Close()
    +			}
    +			child.mode = mode
    +			child.size = record.Size
    +			child.modTime = modTime
    +			child.sha256 = record.Sha256
    +			child.data = stream
    +			child.isDirty = false
    +			child.mu.Unlock()
    +		} else {
    +			child = &FSNode{
    +				inode:   inode,
    +				name:    baseName,
    +				path:    p,
    +				isDir:   false,
    +				mode:    mode,
    +				size:    record.Size,
    +				modTime: modTime,
    +				data:    stream,
    +				sha256:  record.Sha256,
    +				parent:  parent,
    +				isDirty: false,
    +			}
    +			parent.children[baseName] = child
    +		}
    +		parent.modTime = modTime
    +		return nil
     
    -	if meta.NextInode > v.nextInode {
    -		v.nextInode = meta.NextInode
    -	}
    +	case MutationWriteFile:
    +		p := cleanPath(record.Path)
    +		node, err := v.findNodeLocked(p)
    +		if err != nil {
    +			return err
    +		}
    +		node.mu.Lock()
    +		defer node.mu.Unlock()
    +		if len(record.Data) > 0 {
    +			var currentData []byte
    +			if node.data != nil {
    +				_ = node.data.Rewind()
    +				currentData, _ = io.ReadAll(node.data)
    +				_ = node.data.Close()
    +			}
    +			neededLen := record.Offset + int64(len(record.Data))
    +			if neededLen > int64(len(currentData)) {
    +				newBuf := make([]byte, neededLen)
    +				copy(newBuf, currentData)
    +				currentData = newBuf
    +			}
    +			copy(currentData[record.Offset:], record.Data)
    +			if node.size < int64(len(currentData)) {
    +				node.size = int64(len(currentData))
    +			}
    +			node.data = blob.NewByteStreamFromBytes(currentData)
    +		}
    +		if record.Size > 0 {
    +			node.size = record.Size
    +		}
    +		if record.Sha256 != "" {
    +			node.sha256 = record.Sha256
    +		}
    +		if !record.ModTime.IsZero() {
    +			node.modTime = record.ModTime
    +		}
    +		return nil
     
    -	var paths []string
    -	for p := range meta.Entries {
    -		if p != "/" {
    -			paths = append(paths, p)
    +	case MutationTruncateFile:
    +		p := cleanPath(record.Path)
    +		node, err := v.findNodeLocked(p)
    +		if err != nil {
    +			return err
     		}
    -	}
    -	sort.Slice(paths, func(i, j int) bool {
    -		return len(paths[i]) < len(paths[j])
    -	})
    +		node.mu.Lock()
    +		defer node.mu.Unlock()
    +		node.size = record.Size
    +		if record.Sha256 != "" {
    +			node.sha256 = record.Sha256
    +		}
    +		if !record.ModTime.IsZero() {
    +			node.modTime = record.ModTime
    +		}
    +		if node.data != nil {
    +			_ = node.data.Rewind()
    +			currentData, _ := io.ReadAll(node.data)
    +			_ = node.data.Close()
    +			if record.Size < int64(len(currentData)) {
    +				currentData = currentData[:record.Size]
    +			} else if record.Size > int64(len(currentData)) {
    +				newBuf := make([]byte, record.Size)
    +				copy(newBuf, currentData)
    +				currentData = newBuf
    +			}
    +			node.data = blob.NewByteStreamFromBytes(currentData)
    +		}
    +		return nil
     
    -	for _, p := range paths {
    -		entry := meta.Entries[p]
    +	case MutationUnlink:
    +		p := cleanPath(record.Path)
     		parentPath := path.Dir(p)
     		baseName := path.Base(p)
    +		parent, err := v.findNodeLocked(parentPath)
    +		if err != nil {
    +			return nil
    +		}
    +		parent.mu.Lock()
    +		defer parent.mu.Unlock()
    +		if child, ok := parent.children[baseName]; ok {
    +			if child.data != nil {
    +				_ = child.data.Close()
    +			}
    +			delete(parent.children, baseName)
    +		}
    +		return nil
     
    +	case MutationRmdir:
    +		p := cleanPath(record.Path)
    +		parentPath := path.Dir(p)
    +		baseName := path.Base(p)
     		parent, err := v.findNodeLocked(parentPath)
     		if err != nil {
    -			continue
    +			return nil
     		}
    +		parent.mu.Lock()
    +		defer parent.mu.Unlock()
    +		delete(parent.children, baseName)
    +		return nil
     
    -		child := &FSNode{
    -			inode:   entry.Inode,
    -			name:    baseName,
    -			path:    entry.Path,
    -			isDir:   entry.IsDir,
    -			mode:    entry.Mode,
    -			size:    entry.Size,
    -			modTime: entry.ModTime,
    -			sha256:  entry.Sha256,
    -			etag:    entry.ETag,
    -			parent:  parent,
    -			isDirty: false,
    +	case MutationRename:
    +		oldP := cleanPath(record.OldPath)
    +		newP := cleanPath(record.Path)
    +		oldParentPath := path.Dir(oldP)
    +		oldBase := path.Base(oldP)
    +		newParentPath := path.Dir(newP)
    +		newBase := path.Base(newP)
    +		oldParent, err := v.findNodeLocked(oldParentPath)
    +		if err != nil {
    +			return err
     		}
    -		if child.isDir {
    -			child.children = make(map[string]*FSNode)
    +		newParent, err := v.findOrCreateDirParentsLocked(newParentPath)
    +		if err != nil {
    +			return err
    +		}
    +		oldParent.mu.Lock()
    +		defer oldParent.mu.Unlock()
    +		child, ok := oldParent.children[oldBase]
    +		if !ok {
    +			return fmt.Errorf("rename source not found: %s", oldP)
    +		}
    +		if oldParent != newParent {
    +			newParent.mu.Lock()
    +			defer newParent.mu.Unlock()
    +		}
    +		delete(oldParent.children, oldBase)
    +		child.mu.Lock()
    +		child.name = newBase
    +		child.path = newP
    +		child.parent = newParent
    +		if !record.ModTime.IsZero() {
    +			child.modTime = record.ModTime
    +		}
    +		child.mu.Unlock()
    +		newParent.children[newBase] = child
    +		return nil
    +
    +	default:
    +		return fmt.Errorf("unknown mutation type: %s", record.Type)
    +	}
    +}
    +
    +func (v *Volume) replayRecordsLocked(records []*MutationRecord) error {
    +	for _, rec := range records {
    +		if err := v.ApplyRecordLocked(rec); err != nil {
    +			return fmt.Errorf("failed to apply record %v: %w", rec, err)
    +		}
    +	}
    +	return nil
    +}
    +
    +func (v *Volume) replayClientRecordsLocked(records []*wal.ClientRecord) error {
    +	for _, cr := range records {
    +		mut, err := DecodeMutationRecord(cr.Payload)
    +		if err != nil {
    +			return fmt.Errorf("failed to decode mutation record at seq %d: %w", cr.StreamSeq, err)
    +		}
    +		mut.StreamSeq = cr.StreamSeq
    +		if err := v.ApplyRecordLocked(mut); err != nil {
    +			return fmt.Errorf("failed to apply mutation record at seq %d: %w", cr.StreamSeq, err)
    +		}
    +	}
    +	return nil
    +}
    +
    +// ReplayRecords applies an ordered list of mutation records to the volume.
    +func (v *Volume) ReplayRecords(records []*MutationRecord) error {
    +	v.mu.Lock()
    +	defer v.mu.Unlock()
    +	return v.replayRecordsLocked(records)
    +}
    +
    +// ReplayClientRecords decodes and applies an ordered list of WAL client records to the volume.
    +func (v *Volume) ReplayClientRecords(records []*wal.ClientRecord) error {
    +	v.mu.Lock()
    +	defer v.mu.Unlock()
    +	return v.replayClientRecordsLocked(records)
    +}
    +
    +func (v *Volume) LoadFromBackend(ctx context.Context) error {
    +	v.mu.Lock()
    +	defer v.mu.Unlock()
    +
    +	if v.backend != nil {
    +		// 1. Try loading from latest EROFS snapshot
    +		snapshotLoaded := false
    +		latestSnapshotName, err := v.findLatestSnapshotNameLocked(ctx)
    +		if err == nil && latestSnapshotName != "" {
    +			snapshotKey := path.Join("volumes", v.volumeID, "meta", latestSnapshotName)
    +			var imgBuf bytes.Buffer
    +			err := v.backend.GetObject(ctx, "", snapshotKey, 0, 0, &imgBuf)
    +			if err == nil && imgBuf.Len() > 0 {
    +				readerAt := bytes.NewReader(imgBuf.Bytes())
    +				reader, err := erofs.NewReader(readerAt)
    +				if err == nil {
    +					if err := v.loadFromErofsSnapshotLocked(reader, readerAt); err == nil {
    +						snapshotLoaded = true
    +					}
    +				}
    +			}
    +		}
    +
    +		// 2. Fallback to legacy JSON metadata file

    Let's not bother here, we aren't in production so if something is legacy just delete the code

    justinsb justinsb approved these changes on Sep 25, 2026 15:58 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    codebot-robot codebot-robot
    Labels
    risk: low confidence: 70.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 56.2% (MEDIUM) · Higher = larger blast radius
    56.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 70.8% · Lower = rushed or shallow review
    70.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 16.4% · Safe to merge
    16.4%