syncservice

package
v0.0.0-...-0b698e0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2026 License: Apache-2.0, MIT Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Sync operation handoff

syncservice is the exact-key control and receipt layer for arm sync-worker. It binds syncreconcile output to ARM's existing leased SSH admission and to syncfs native publication. It does not create another transport or grant file authority. This package is wired to private Manager-owned source/destination workers and the durable database namespace; public CLI/direct/routed dispatch remains closed.

Direct leased SSH sequence

  1. Both endpoints hold reviewed roots and scan the same selection with syncfs.Scan. The initiating endpoint calls syncreconcile.Reconcile and reviews its digest, exact actions, conflicts, identities, policies, resource promises, and generation. Binding must identify the authorized account and use syncfs.Root.NativeID() for each held root; a path string alone is insufficient. Call syncfs.VerifyPlanRoot before source materialization and publication, and retain the held handles through the operation. Unresolved conflicts prevent an intent.
  2. NewIntent recalculates that exact plan, records the complete selected and candidate-name manifest, source and destination CPU/memory/disk promises, original sync/SSH key, fixed worker-command SHA-256, and the proposed next baseline. Manifest and record bytes are each capped at 64 MiB, and manifest construction is limited by the smaller endpoint memory promise. The source Manager charges planning and worker resources, then calls ReserveTx with its own held-root scan and commits before creating or dispatching an SSH invocation. It also uses the existing SSH source intention fence under that same key.
  3. The destination Manager authenticates the original SSH identity/account, grant, fixed worker command, and root. Its held-root syncfs.Scan must independently reproduce the destination manifest and native name keys; source-supplied rows are comparison evidence, not destination observations. It calls ReserveTx with that independent observation inside the transaction that admits the leased SSH process, charging its destination resources there. ReserveTx rebuilds the plan from the manifest and the destination's currently confirmed baseline. A changed plan or generation is refused before any file effect. WritePreparation/ReadPreparation use a versioned length frame, explicit wire byte cap, and counted manifest decode. A token preflight charges nested collection, decoded-string, and canonical JSON escaping overhead before typed decoding, including the proposed baseline maps and action arrays. ReadPreparation requires the Manager's active memory admission before it allocates the frame body; the request's resource promise is not that hold.
  4. The workers materialize only reviewed source actions into private staging, using syncfs.BuildSourceManifest, SeedReceiverBasis, and FinalizeStageDirectories around the bounded rsync exchange. These verify source and staged SHA-256 plus selected metadata. syncfs requires the receiver's workspace disk reservation and verifies all staged effects before publication. The receiver uses Ledger as syncfs.Journal in NewPublisher/ApplyAll. A prepared effect cannot be replayed; a lost outcome remains inspectable under the original key.
  5. After ApplyAll, held-root recheck and worker settlement, each endpoint calls CompleteOwnSide. The authenticated SSH control stream exchanges SideReceipt values; RecordPeerReceipt persists the peer's exact value. Each endpoint calls ConfirmBaseline only after both receipts exist. A lost confirmation reply is resolved with Ledger.Lookup, never another apply.

Ledger.Lookup is read-only. It validates each prepared receipt and outcome against the original intent, and checks a completed side's effect roster and digest before exposing the original intent, manifest, effect receipts, and endpoint receipts. It neither retries transport nor cleans stage or quarantine. Retained preimages and stage remain under the original operation until a separately reviewed cleanup. If the exact SSH destination returns a durable nonexecution fence, the source may call RecordNonexecution with that fence. The sealed original remains lookup-only and permits a separately reviewed first-run key; an unknown or admitted original never permits a new-key escape.

Required integration changes outside this package

  • Manager: add a typed sync admission around existing AcquireSSHCommitted. The destination sync reservation and SSH admission need one SQLite transaction, so merely calling the two existing entrypoints in sequence is insufficient. The source needs a durable pre-dispatch sync reservation and the existing SSH source intent. Bind each admitted resource promise to the actual CPU, memory, disk, TTL, grant, and worker lifecycle. syncservice checks positive promises and a control/stage/preimage lower bound; those checks do not establish that Manager charged the resources. Do not dispatch or publish until authoritative admission proves the charge.
  • Database: install and prove OperationsSchema, OpenGenerationSchema, EffectsSchema, and BaselinesSchema with a version marker and startup/reset/Stop recovery. Configure SQLite synchronous=FULL or stronger with WAL or a rollback journal on every writing connection; mutating methods verify both settings on their transaction. Reject missing prior namespaces or partial records as uncertain evidence.
  • SSH worker/control: use one fixed, reviewed arm sync-worker entry and compare Intent.WorkerCommandSHA256 and Intent.SSHControlSHA256 with the existing exact SSH control commitment. Send bounded versioned control messages over the authenticated leased stream for prepare, stage, apply, exact-key lookup, receipt exchange, and confirm. Do not use a shell-selected rsync binary or restart a timed-out worker.
  • Native transfer: rsyncengine.Run currently sends a supplied entire root. Give it only the private tree built by syncfs.BuildSourceManifest, including reviewed SourcePath to Path remapping. Recheck source hashes, stage hashes, root identity, and selected paths. SeedReceiverBasis copies or clones the reviewed basis under a charged receiver reservation. Retained preimages and transfer temporary files also count against that admission. The integrated native syncfs overlay provides Root.NativeID, VerifyPlanRoot, BuildSourceManifest, SeedReceiverBasis, and FinalizeStageDirectories. The local publication test binds both native roots, refuses a different receiver and uses NewBoundPublisher with the durable ledger. It does not exercise authenticated SSH transfer or actual Manager charging. Stage sizes are logical lower bounds: admission must account for allocation, inode and temporary/preimage overhead on the actual source and receiver filesystems; the state-directory disk pool alone cannot authorize a different volume.

Manager installs and proves this namespace during startup. Used sync history currently blocks reset and Stop until exact native cleanup/recovery proof is integrated; schema installation alone does not authorize public sync dispatch. The private Manager adapter now joins source reservations with local leases and destination reservations with the exact SSH fence, operation and lease before the process gate. It refuses a different filesystem and retains every admitted sync charge until a later exact recovery/cleanup join; no public fixed-worker caller is enabled yet.

The Manager adapter first admits a private preparation owner (one core, 768 MiB memory, 1 MiB scratch), before its expensive validation and native scan. Remote preparation consumes the original peer's aggregate grant. After native preparation returns, exact-owner accounting is atomically exchanged for the final sync/SSH charge; retained control data must fit that final promise. Only the original synchronous worker's return and verified scratch cleanup settle that hold. Cancellation/expiry/Stop cannot substitute for join; unknown cleanup/persistence and recovered owners remain charged. Failed preparations retain their original key history and cannot be adopted as new owners. This does not yet authorize caller-side planning before Manager entry. Outgoing materialization, receiver copies/preimages and control journal space are included in admission floors; the native device/fsid and sampled fsid/pool are bound and rechecked. These are cooperative floors, not physical allocation or RSS enforcement, and the public runner/recovery gates above remain open.

InspectPair reads both original ledgers without replaying effects. It compares intents, manifests and receipt copies; every endpoint claiming confirmation must retain both receipts and its exact proposed baseline, even when the peer is pending. Joint confirmation is a protocol result, not resource settlement. The separate local Manager.InspectSyncKey view preserves the charged lease state alongside operation and receipt state. These helpers authenticate neither supplied database handles nor a future remote requester; public authenticated lookup and exact native cleanup remain separate gates.

Documentation

Overview

Package syncservice owns the exact-key synchronization operation and receipt contract between ARM's leased SSH worker, syncreconcile, and syncfs. It does not open SSH channels, reserve Manager resources, or mutate selected files.

Index

Constants

View Source
const (
	// FixedWorkerCommand is the exact versioned SSH exec commitment shared by
	// Manager admission and the private worker. It does not enable a CLI entry.
	FixedWorkerCommand = "arm sync-worker --protocol=1"
	Schema             = 1
	MaxRecordBytes     = 64 << 20
	MaxManifestBytes   = 64 << 20
)
View Source
const BaselinesSchema = `CREATE TABLE sync_baselines (pair TEXT PRIMARY KEY,generation INTEGER NOT NULL,seal TEXT NOT NULL,record BLOB NOT NULL)`
View Source
const ChargedScopeFinalIndex = `CREATE UNIQUE INDEX sync_charged_scopes_final ON sync_charged_scopes(final_lease)`
View Source
const ChargedScopePreparationIndex = `CREATE UNIQUE INDEX sync_charged_scopes_preparation ON sync_charged_scopes(preparation_lease)`
View Source
const ChargedScopeProjectIndex = `CREATE UNIQUE INDEX sync_charged_scopes_project ON sync_charged_scopes(provider,mount_id,project_id)`
View Source
const ChargedScopeSchema = `` /* 944-byte string literal not displayed */

ChargedScopeSchema is the immutable version-3 original-scope row shape. It is installed only in a fresh, dedicated sync namespace. A row is evidence for recovery, never a reconstructed execution capability.

View Source
const EffectsSchema = `` /* 197-byte string literal not displayed */
View Source
const MaxPreparationBytes = MaxRecordBytes + MaxManifestBytes + 1<<20
View Source
const OpenGenerationSchema = `CREATE UNIQUE INDEX sync_open_generation ON sync_operations(pair,side,generation) WHERE state!='sealed'`
View Source
const OperationsSchema = `` /* 285-byte string literal not displayed */

These tables belong to the Manager's proven state schema. The Manager must install and prove them, and must reserve destination sync intent in the same transaction that admits the exact leased SSH execution. No lazy schema creation is permitted after an operation namespace has been used.

View Source
const WorkspacesSchema = `` /* 241-byte string literal not displayed */

Variables

View Source
var (
	ErrKeyExists   = errors.New("sync key already reserved; inspect the original key")
	ErrUnknown     = errors.New("sync outcome unknown; inspect the original key without replay")
	ErrUnconfirmed = errors.New("both exact endpoint completion receipts are required")
)

Functions

func ConfirmBaselineTx

func ConfirmBaselineTx(ctx context.Context, tx *sql.Tx, key string, side syncreconcile.Side) (syncreconcile.ConfirmedBaseline, error)

ConfirmBaselineTx must run after matching dual receipts are durable. The generation update is compare-and-swap against the prior baseline seal. The source and destination each call it locally; a lost reply is lookup-only.

func InstallSchemaTx

func InstallSchemaTx(ctx context.Context, tx *sql.Tx) error

func LoadBaseline

LoadBaseline is read-only and returns nil only when the exact ordered pair has no confirmed generation. A missing row for a previously used pair must be treated as lost evidence by the Manager, not declared a first run.

func NewIntent

func NewIntent(key, workerCommandSHA256, sshControlSHA256, reason string, side syncreconcile.Side, req syncreconcile.Request, reviewed syncreconcile.Plan, local, remote model.Resources, created time.Time) (Intent, []ManifestRow, error)

NewIntent recalculates the reviewed plan, so an unrelated Plan cannot be paired with different observations. A caller supplies the native snapshots, reviewed resource promises, and one exact SSH execution key.

func PreparationFootprint

func PreparationFootprint(ctx context.Context, p Preparation, admission DecodeAdmission) (int64, error)

PreparationFootprint checks the canonical byte/structure allowance while the original preparation is still charged. This is a conservative policy check for handoff at either endpoint, not an allocation or RSS guarantee.

func ReconcileIntent

func ReconcileIntent(i Intent, rows []ManifestRow, baseline *syncreconcile.ConfirmedBaseline) (syncreconcile.Plan, error)

ReconcileIntent reconstructs the exact reviewed plan on the destination from the selected manifest and its locally confirmed baseline. It refuses a changed generation, resolution, native name key, or proposed result.

func ReserveTx

func ReserveTx(ctx context.Context, tx *sql.Tx, i Intent, rows []ManifestRow, observed syncreconcile.Snapshot) error

ReserveTx is the sole dispatch gate. A returned error, including a commit uncertainty in the caller's transaction, never authorizes SSH dispatch.

func VerifyDurableSQLite

func VerifyDurableSQLite(ctx context.Context, db *sql.DB) error

VerifyDurableSQLite checks the connection's durability setting before any intent or effect journal is trusted as a crash fence.

func WritePreparation

func WritePreparation(w io.Writer, p Preparation) error

Types

type DecodeAdmission

type DecodeAdmission interface {
	CheckActive(context.Context) error
	MemoryBytes() int64
}

DecodeAdmission must be backed by the Manager's live, charged memory hold. A resource value copied from the untrusted preparation request is not an admission. The worker supplies this before reading a preparation frame.

type Intent

type Intent struct {
	Schema              int                             `json:"schema"`
	Key                 string                          `json:"key"`
	SSHKey              string                          `json:"ssh_key"`
	WorkerCommandSHA256 string                          `json:"worker_command_sha256"`
	SSHControlSHA256    string                          `json:"ssh_control_sha256"`
	Reason              string                          `json:"reason"`
	Side                syncreconcile.Side              `json:"side"`
	Binding             syncreconcile.Binding           `json:"binding"`
	Direction           syncreconcile.Direction         `json:"direction"`
	LocalPolicy         syncreconcile.Policy            `json:"local_policy"`
	RemotePolicy        syncreconcile.Policy            `json:"remote_policy"`
	PlanDigest          string                          `json:"plan_digest"`
	Generation          uint64                          `json:"generation"`
	PriorSeal           string                          `json:"prior_seal,omitempty"`
	ManifestDigest      string                          `json:"manifest_digest"`
	LocalResources      model.Resources                 `json:"local_resources"`
	RemoteResources     model.Resources                 `json:"remote_resources"`
	Actions             []syncreconcile.Action          `json:"actions"`
	Resolutions         []syncreconcile.Resolution      `json:"resolutions,omitempty"`
	Proposal            syncreconcile.ConfirmedBaseline `json:"proposal"`
	Created             time.Time                       `json:"created"`
}

Intent is reserved durably at the source before SSH dispatch and at the destination in the same transaction as leased SSH admission. Local is the initiating endpoint; remote is the SSH destination.

func (Intent) Validate

func (i Intent) Validate() error

type Ledger

type Ledger struct {
	DB   *sql.DB
	Key  string
	Side syncreconcile.Side
	// contains filtered or unexported fields
}

Ledger is bound to one endpoint's original operation key. Its Prepare and Outcome methods implement syncfs.Journal with committed SQLite transactions. Manager must use a durable SQLite connection and rollback/WAL journal.

func (*Ledger) CompleteOwnSide

func (l *Ledger) CompleteOwnSide(ctx context.Context) (SideReceipt, error)

CompleteOwnSide records one exact completion only after every expected effect has an applied durable outcome. The caller must recheck the held root and resource obligations before invoking it. It never treats a process exit or missing effect row as successful publication.

func (*Ledger) ConfirmBaseline

func (l *Ledger) ConfirmBaseline(ctx context.Context) (syncreconcile.ConfirmedBaseline, error)

func (*Ledger) Lookup

func (l *Ledger) Lookup(ctx context.Context) (Lookup, error)

Lookup reads original-key evidence without starting or retrying work.

func (*Ledger) Outcome

func (l *Ledger) Outcome(ctx context.Context, r syncfs.Receipt) error

func (*Ledger) Prepare

func (l *Ledger) Prepare(ctx context.Context, r syncfs.Receipt) error

func (*Ledger) RecordNonexecution

func (l *Ledger) RecordNonexecution(ctx context.Context, seal model.SSHKeyFence) error

RecordNonexecution preserves a destination's exact SSH seal only when this source operation has no native effect or endpoint receipt. It releases the pair's first-run generation for a separately reviewed new key, while the original sealed record remains durable and lookup-only.

func (*Ledger) RecordPeerReceipt

func (l *Ledger) RecordPeerReceipt(ctx context.Context, r SideReceipt) error

RecordPeerReceipt must be called only after the Manager authenticates the opposite endpoint over the leased SSH control channel. A duplicate exact receipt is harmless; it never repeats a native effect.

func (*Ledger) RecordWorkspace

func (l *Ledger) RecordWorkspace(ctx context.Context, role string, selected, parent *syncfs.Root, work *syncfs.Workspace) error

RecordWorkspace binds a newly created marked workspace to the original operation before staging. Failure retains the charged obligation and native workspace; no mutation or cleanup may follow an uncertain commit.

func (*Ledger) Workspaces

func (l *Ledger) Workspaces(ctx context.Context) ([]WorkspaceRecord, error)

Workspaces lists only bounded, shaped durable locators. The caller must reopen native roots to inspect them; rows alone never grant cleanup.

type Lookup

type Lookup struct {
	Intent        Intent
	Manifest      []ManifestRow
	State         string
	Effects       []syncfs.Receipt
	LocalReceipt  *SideReceipt
	RemoteReceipt *SideReceipt
	Nonexecution  *model.SSHKeyFence
}

type ManifestRow

type ManifestRow struct {
	Side    syncreconcile.Side   `json:"side"`
	Path    string               `json:"path"`
	NameKey string               `json:"name_key"`
	Entry   *syncreconcile.Entry `json:"entry,omitempty"`
}

ManifestRow records either an observed selected entry or an absent candidate name. The latter binds native case/Unicode and exclusion checks at both ends.

type PairRecovery

type PairRecovery struct {
	Key              string
	PlanDigest       string
	Generation       uint64
	LocalState       string
	RemoteState      string
	LocalReceipt     *SideReceipt
	RemoteReceipt    *SideReceipt
	JointlyConfirmed bool
	NeedsAttention   bool
}

PairRecovery is a read-only comparison of the two original endpoint keys. NeedsAttention never authorizes a replay, cleanup, or allocation release. A caller must obtain each Ledger through its authenticated endpoint route; this comparison does not authenticate a supplied database connection.

func InspectPair

func InspectPair(ctx context.Context, local, remote *Ledger) (PairRecovery, error)

InspectPair compares exact durable intent, manifest, receipts and confirmed baselines at both endpoints. Each endpoint is read independently, so a concurrent state change can cause a conservative error or attention result. It never starts a worker or writes a baseline.

type Preparation

type Preparation struct {
	Version  int           `json:"version"`
	Intent   Intent        `json:"intent"`
	Manifest []ManifestRow `json:"manifest"`
}

Preparation is the first length-framed control message on the fixed arm sync-worker SSH stream. Binary rsync payload follows only after the destination has authenticated, reconstructed, and durably reserved it.

func ReadPreparation

func ReadPreparation(ctx context.Context, r io.Reader, admission DecodeAdmission) (Preparation, error)

ReadPreparation refuses oversized wire bodies before allocation, then streams manifest rows through an explicit count limit before building the decoded slice. The caller must call ReserveTx against its local baseline before acknowledging preparation or accepting any transfer payload.

func ReadPreparationWithFootprint

func ReadPreparationWithFootprint(ctx context.Context, r io.Reader, admission DecodeAdmission) (Preparation, int64, error)

ReadPreparationWithFootprint returns the same conservative byte/structure budget checked during decoding. This is policy accounting, not measured RSS or a new admission: the caller still needs the original charged decoder.

type SideReceipt

type SideReceipt struct {
	Key            string             `json:"key"`
	PlanDigest     string             `json:"plan_digest"`
	Generation     uint64             `json:"generation"`
	Side           syncreconcile.Side `json:"side"`
	RootID         string             `json:"root_id"`
	ManifestDigest string             `json:"manifest_digest"`
	BaselineSeal   string             `json:"baseline_seal"`
	EffectCount    int                `json:"effect_count"`
	EffectsDigest  string             `json:"effects_digest"`
}

SideReceipt is emitted only after all of one endpoint's expected native effects have durable applied outcomes and its selected root is rechecked. The receiving Manager must authenticate the peer carrying the other side's receipt; this struct is not itself a signature.

type WorkspaceRecord

type WorkspaceRecord struct {
	Role, Path, RootID, ParentID, BaseID string
	DiskBytes                            int64
}

WorkspaceRecord is a durable locator, not authority to delete files or release a disk promise. Native roots must be reopened and checked separately.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL