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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 122 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# Omloom engineering and review guidance

Omloom is an infrastructure source of truth and a workspace for reviewing and
recording changes. Optimize for useful daily work with partial knowledge,
correct shared state, and bounded retrieval and mutation costs.

## Code Review Rules

### Establish the behavior before proposing a mechanism

Trace the actual producer, transformations, authorization, consumers and commit
point. A finding should name a concrete input/state, the violated invariant and
the observable consequence. Distinguish a reproducible defect from an unresolved
product choice or an optional improvement. Prefer no finding over speculation.
Review the proposed remedy as critically as the symptom: identify the existing
owner that should enforce the invariant before adding state or another check.

### Justify persisted data and its full lifecycle

For new fields, rows, indexes, snapshots, counters or partitions, identify the
actual delivered consumer or recovery invariant. Check the authoritative owner,
write trigger, lookup pattern, cardinality, bounds and reclamation. Flag duplicate
authority, unchanged-input writes, read-triggered persistence and historical
payloads without consumers. A transport field is not a storage requirement.
Small fencing, replay and recovery records have real consumers; do not recommend
deleting them merely to reduce bytes. Expired evidence or deadlines do not prove
that an external effect never happened or that reserved capacity is free.

### Enforce database invariants at their owner

Use typed, appropriately scoped identities and database-enforced uniqueness,
CAS and transactions. A read followed by a write or a process-local lock cannot
enforce exclusivity across concurrent writers. Commit coupled accepted state,
reservation, idempotency, required audit and delivery intent atomically. Keep
external I/O outside short transactions, with the durable intent, fencing and
revision checks needed to reconcile an uncertain result. Entry validation and
commit-time revalidation may both be necessary; share their decision logic.

Design the physical schema for real lookups and updates. A protobuf record is
not a storage schema; avoid whole-message blobs when consumers need independent
fields. Do not copy ownership, placement or lifecycle state into competing
authoritative records. Derived caches and projections need a concrete latency
benefit, bounded size and consistent invalidation/rebuild behavior. Reuse the
existing owner rather than surrounding duplicate state with more guards.

### Protect current reads and minimize write amplification

Current-state retrieval must not scan or replay unbounded history. Fetch the
selected scope and fields, paginate with stable ordering, and descend only as
far as the actual view or operation requires. Counts and pages must agree under
their promised read revision. Check visibility before aggregation and export.
Inspect real query plans and representative latency when proposing indexes or
query rewrites; an index name alone does not prove selective execution.

Reads must not persist access counters, last-read times, cache touches or new
snapshots without a delivered consumer. Identical input must not copy payloads
or create duplicate domain history. Freshness, source checkpoints, audit and
authority transitions may still require a minimal update even when the displayed
value is unchanged. Batch or coalesce only when independent source evidence,
ordering, meaningful transitions and required durability remain intact.

### Bound retention and verify recovery and reclamation

For growing data, check the required lifetime or completion condition, count/byte
bounds, cleanup owner and actual reclamation path. Current authoritative state
lives until domain removal; it does not acquire an arbitrary TTL. Evidence
freshness, user-visible history, replay protection and physical reclamation have
different lifetimes. Retain detailed history only for a named consumer, with
explicit time/version limits; do not introduce universal snapshots or an event
log merely because the database supports them.

Cleanup must be bounded, resumable and safe across replicas and interrupted runs.
Logical deletion does not prove that blobs, old MVCC versions or disk allocation
were reclaimed. Include indexes, journals and maintenance headroom in storage
claims. Never expire unresolved effects, active holds or required restore/replay
checkpoints to make quota available. Bound admission and expose unresolved work;
backups must not resurrect expired authority or completed effects.

Credential providers own reusable secrets and monitoring providers own telemetry
history. Do not mirror their stores or retain tokens, transient credentials or
whole provider responses in inventory, audit, delivery payloads, logs or backups.
Verify affected consumers with concurrent admission, unchanged-input write cost,
bounded reads and interrupted cleanup/recovery where those invariants change.

### Separate navigation, authority and aggregation

A focused resource, selected view and authorization grant serve different
purposes. Do not turn navigation state into a persisted dimension by default.
For aggregate disclosure, establish the intended contributing population and
the reader's authority over it. Adding focus-specific buckets is not a substitute
for authorization. Enforce resource and field access at the store boundary before
returning protected values or counts; UI filtering cannot supply that guarantee.

### Preserve partial knowledge and reduce user decisions

Unknown, explicitly zero, absent, stale, restricted and conflicting facts are
different states. Request missing facts only when the particular operation needs
them. Drafting and recording actual work must not require certification of an
entire infrastructure. Conversely, unknown required facts cannot certify fit,
free capacity or working service. Do not require redundant user input when the
authoritative context already determines it, invent an identity from a label,
or multiply modes and controls without a concrete user task.

### Keep domain geometry and mechanisms general

Rack U numbering is an optional declared mounting grid, not a universal enclosure
coordinate system. Nested bays and equipment use their enclosing coordinate
frame and actual placement constraints; names and pictures do not establish
orientation, dimensions, mounting compatibility or occupancy. Reuse the shared
plan, requirement, reservation and recovery mechanisms instead of introducing a
second workflow or copying physical state into another authority.

### Review work and tests at the required granularity

Flag whole-graph reads, N+1 queries, unnecessary decoding, allocations and writes
against the actual requested projection. An index or materialized copy needs a
demonstrated access-pattern benefit and a consistent update lifecycle.
For a correctness defect, identify a regression scenario that fails on the
unfixed path and preserves the surrounding valid behavior. Test the owning
boundary and real consumers. Do not recommend weaker assertions, silent fallbacks,
larger timeouts or unrelated full-suite reruns as a substitute for diagnosis.
Use stable Rust, nextest for Rust tests, and separate doctests.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ including bounded quantities, model alternatives and supported exclusions,
then be refined without changing their identity.
The workspace can [check recorded requirements](docs/inventory.md#recorded-requirements)
against permitted current facts, preserving missing, stale and conflicting evidence.
It includes [physical planning](docs/inventory.md#physical-plans-and-cable-ends) with exact
rack elevations, cable ends, material requirements, reservations and reviewed
component replacement. Manual results remain separate from verified service health.

## License

Expand Down
1 change: 1 addition & 0 deletions crates/omloom-app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ pub fn policy() -> Policy {
bytes: 2 * 1_048_576,
},
batch_rows: 128,
physical_reservation_max_ms: 86_400_000,
}
}
pub fn fixture(name: &str) -> Result<Context, &'static str> {
Expand Down
32 changes: 32 additions & 0 deletions crates/omloom-contracts/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ fn main() -> Result<(), Box<dyn Error>> {
.boxed(".omloom.workspace.v1.Reply.result.detail")
.boxed(".omloom.workspace.v1.Reply.result.vm_placement_review")
.boxed(".omloom.workspace.v1.HostImport.report")
// Keep the request stack bound; allocate this volume only for an explicit coverage assertion.
.boxed(".omloom.workspace.v1.PhysicalDefinition.occupancy_coverage")
.boxed(".omloom.workspace.v1.PhysicalDefinition.rack_grid")
.boxed(".omloom.workspace.v1.PhysicalDefinition.clearance")
.boxed(".omloom.workspace.v1.PhysicalMaterial.physical")
.boxed(".omloom.workspace.v1.PhysicalReplacement.feedback")
.file_descriptor_set_path(&descriptor)
.compile_protos(&[workspace], &["../../proto"])?;
let set = FileDescriptorSet::decode(fs::read(descriptor)?.as_slice())?;
Expand Down Expand Up @@ -65,10 +71,36 @@ fn main() -> Result<(), Box<dyn Error>> {
&& matches!(field.name(), "candidates" | "excluded")
{
16
} else if message.name() == "PowerPathRequirement"
&& matches!(field.name(), "sources" | "boundaries")
{
8
} else if (message.name() == "EvaluateRequirements" && field.name() == "nodes")
|| (message.name() == "RequirementGroup" && field.name() == "members")
|| (message.name() == "PhysicalPlan" && field.name() == "steps")
|| (message.name() == "PhysicalView" && field.name() == "definitions")
|| (message.name() == "PhysicalCompletion"
&& matches!(field.name(), "completed_steps" | "not_performed_steps"))
|| (message.name() == "PhysicalPlan" && field.name() == "materials")
|| (message.name() == "PhysicalMaterial" && field.name() == "allocations")
|| (message.name() == "PhysicalReplacement" && field.name() == "endpoints")
|| (message.name() == "PhysicalEndpointMappings" && field.name() == "pairs")
|| (message.name() == "PhysicalCableEnd" && field.name() == "channels")
|| (message.name() == "PhysicalChannelSet" && field.name() == "channels")
|| (message.name() == "PhysicalDefinition" && field.name() == "channels")
{
64
} else if message.name() == "PhysicalMaterial" && field.name() == "specifications" {
12
} else if message.name() == "PhysicalView"
&& matches!(
field.name(),
"occupancy" | "plans" | "positions" | "replacement_quality"
)
{
25
} else if message.name() == "PhysicalView" && field.name() == "items" {
256
} else {
0
}
Expand Down
53 changes: 31 additions & 22 deletions crates/omloom-contracts/src/equipment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,29 +221,13 @@ fn identity(value: &Option<EquipmentReference>) -> (&str, &str, &str) {
None => ("", "", ""),
}
}
/// One bounded semantic encoding for retries, changed-only storage and CSV.
/// Candidate/exclusion order is irrelevant; source and interpretation basis are not.
pub fn encode(value: &EquipmentClaim) -> Result<Vec<u8>, Error> {
/// Normalize an owned bounded claim for changed-only storage and returned plans.
pub fn canonicalize(value: &mut EquipmentClaim) -> Result<(), Error> {
validate(value)?;
let canonical = match &value.assertion {
Some(equipment_claim::Assertion::Quantity(q)) => {
q.scale == 0
|| q.lower.is_some_and(|n| n % 10 != 0)
|| q.upper.is_some_and(|n| n % 10 != 0)
}
Some(equipment_claim::Assertion::Alternatives(v)) => {
v.candidates.is_sorted_by(|a, b| {
(&a.value, identity(&a.reference)) <= (&b.value, identity(&b.reference))
}) && v.excluded.is_sorted_by(|a, b| {
(&a.value, identity(&a.reference)) <= (&b.value, identity(&b.reference))
})
}
_ => true,
};
if canonical {
return Ok(value.encode_to_vec());
}
let mut value = value.clone();
canonicalize_validated(value);
Ok(())
}
fn canonicalize_validated(value: &mut EquipmentClaim) {
if let Some(equipment_claim::Assertion::Quantity(q)) = &mut value.assertion {
while q.scale > 0
&& q.lower.is_none_or(|n| n % 10 == 0)
Expand All @@ -266,6 +250,31 @@ pub fn encode(value: &EquipmentClaim) -> Result<Vec<u8>, Error> {
(&a.value, identity(&a.reference)).cmp(&(&b.value, identity(&b.reference)))
});
}
}
/// One bounded semantic encoding for retries, changed-only storage and CSV.
/// Candidate/exclusion order is irrelevant; source and interpretation basis are not.
pub fn encode(value: &EquipmentClaim) -> Result<Vec<u8>, Error> {
validate(value)?;
let canonical = match &value.assertion {
Some(equipment_claim::Assertion::Quantity(q)) => {
q.scale == 0
|| q.lower.is_some_and(|n| n % 10 != 0)
|| q.upper.is_some_and(|n| n % 10 != 0)
}
Some(equipment_claim::Assertion::Alternatives(v)) => {
v.candidates.is_sorted_by(|a, b| {
(&a.value, identity(&a.reference)) <= (&b.value, identity(&b.reference))
}) && v.excluded.is_sorted_by(|a, b| {
(&a.value, identity(&a.reference)) <= (&b.value, identity(&b.reference))
})
}
_ => true,
};
if canonical {
return Ok(value.encode_to_vec());
}
let mut value = value.clone();
canonicalize_validated(&mut value);
Ok(value.encode_to_vec())
}

Expand Down
24 changes: 24 additions & 0 deletions crates/omloom-contracts/src/equipment/tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,28 @@
use super::*;

// Owned plans and the persisted encoding must share normalization, including retry order and fixed-point spelling.
#[test]
fn owned_claim_canonicalization_matches_encoding_and_is_idempotent() {
let mut value = possible();
let encoded = encode(&value).expect("valid claim");
canonicalize(&mut value).expect("valid owned claim");
assert_eq!(value.encode_to_vec(), encoded);
let previous = value.clone();
canonicalize(&mut value).expect("already canonical claim");
assert_eq!(value, previous);
let mut quantity = EquipmentClaim {
basis: "Recorded physical measurement".into(),
assertion: Some(equipment_claim::Assertion::Quantity(QuantityRange {
lower: Some(1200),
upper: None,
scale: 2,
unit: "mm".into(),
})),
};
let encoded = encode(&quantity).expect("valid measurement");
canonicalize(&mut quantity).expect("owned measurement");
assert_eq!(quantity.encode_to_vec(), encoded);
}
fn possible() -> EquipmentClaim {
EquipmentClaim {
basis: "Front label and visible bays".into(),
Expand Down
1 change: 1 addition & 0 deletions crates/omloom-contracts/src/ids.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ id!(SourceId);
id!(AuthorityId);
id!(RelationId);
id!(OperationId);
id!(PlanId);
id!(ScanId);
id!(TrustId);
id!(CredentialBindingId);
Expand Down
85 changes: 85 additions & 0 deletions crates/omloom-contracts/tests/workspace.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,91 @@
use omloom_contracts::{Error, Limits, MemoryBudget, decode_workspace, workspace as api};
use prost::Message;

// The evaluator's eight-reference bound must reject oversized frames before decoded allocation.
#[test]
fn power_path_reference_counts_are_bounded_before_decode() {
for sources in [true, false] {
for count in [8, 9] {
let refs = vec![Default::default(); count];
let mut paths = api::PowerPathRequirement::default();
if sources {
paths.sources = refs;
} else {
paths.boundaries = refs;
}
let bytes = api::Request {
command: Some(api::request::Command::EvaluateRequirements(
api::EvaluateRequirements {
nodes: vec![api::RequirementNode {
expression: Some(api::requirement_node::Expression::PowerPaths(paths)),
}],
..Default::default()
},
)),
..Default::default()
}
.encode_to_vec();
let budget = MemoryBudget::new(16 * 1_048_576);
let decoded = decode_workspace(&bytes, Limits::default(), &budget);
if count == 9 {
assert!(matches!(decoded, Err(Error::Limit)));
} else {
assert!(decoded.is_ok());
}
drop(decoded);
assert_eq!(budget.used(), 0);
}
}
}

// Physical wire containers enforce repeated bounds before prost allocates their vectors.
#[test]
fn physical_channels_and_endpoint_maps_are_bounded_before_decode() {
let budget = MemoryBudget::new(16 * 1_048_576);
let channels = api::Request {
working: None,
command: Some(api::request::Command::Physical(api::Physical {
action: Some(api::physical::Action::Define(api::PhysicalDefinitionEdit {
definition: Some(api::PhysicalDefinition {
channels: vec![1; 65],
..Default::default()
}),
})),
})),
}
.encode_to_vec();
assert!(matches!(
decode_workspace(&channels, Limits::default(), &budget),
Err(Error::Limit)
));
assert_eq!(budget.used(), 0);
let mappings = api::Request {
working: None,
command: Some(api::request::Command::Physical(api::Physical {
action: Some(api::physical::Action::Save(api::PhysicalSave {
plan: Some(api::PhysicalPlan {
steps: vec![api::PhysicalStep {
action: Some(api::physical_step::Action::Replacement(
api::PhysicalReplacement {
endpoints: vec![Default::default(); 65],
..Default::default()
},
)),
..Default::default()
}],
..Default::default()
}),
})),
})),
}
.encode_to_vec();
assert!(matches!(
decode_workspace(&mappings, Limits::default(), &budget),
Err(Error::Limit)
));
assert_eq!(budget.used(), 0);
}

// Omitted wire input cannot implicitly request an exclusive allocation.
#[test]
fn network_sharing_requires_an_explicit_mechanism() {
Expand Down
Loading
Loading