File size: 12,478 Bytes
32b4893 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 | # NraayTensor Pascal Reference - Integration Guide
## Quick Start
### Build the Reference Implementation
```bash
cd pascal/
make build
./nraay_tensor_ref
```
Expected output:
```
================================================================
NraayTensor Reference Implementation (Free Pascal)
Semantic validation layer for Rust tensor-core library
================================================================
--- Semantic Layer ---
...
Test Results:
Total: 10
Passed: 10
Failed: 0
All tests PASSED!
```
## Using the Reference as an Oracle
The Pascal reference implementation can validate Rust tensor operations through conformance testing.
### Pattern 1: Direct Descriptor Comparison
After a Rust tensor operation, export the resulting descriptor and validate:
```rust
// Rust side
let t = NraayTensor::new(vec![3, 4])?;
let descriptor = t.to_c_descriptor();
```
```pascal
// Pascal side
uses validation;
var
desc: TTensorDescriptor;
result: TTestResult;
begin
// Import descriptor from Rust FFI
result := CompareDescriptors(expected_desc, desc);
if result = TEST_PASS then
writeln('Descriptor matches!')
else
writeln('Descriptor mismatch: ', result);
end;
```
### Pattern 2: Operation Validation
After each operation (ALLOC, SLICE, TRANSPOSE, MATERIALIZE), call oracle:
```pascal
uses validation, tensor;
// After Rust SLICE operation
sliced := Slice(t, ranges);
report := ValidateSlice(t, sliced);
if report.passed then
writeln('Slice valid: ', report.details)
else
begin
writeln('Slice failed: ', report.details);
halt(1);
end;
```
### Pattern 3: Governance Verification
After any complex operation, verify all 5 lemmas:
```pascal
uses governance, tensor;
var
buf: PBuffer;
valid: boolean;
begin
buf := t.data.buffer;
valid := ValidateAllLemmas(t.descriptor, buf);
if valid then
writeln('All governance lemmas verified')
else
writeln('Governance violation detected!');
end;
```
### Pattern 4: Conformance Test Suite
For regression testing, import and call Pascal tests:
```pascal
uses tests;
var
stats: TTestStats;
begin
stats := RunAllTests;
writeln('Conformance tests: ', stats.passed, '/', stats.total_tests);
if stats.failed > 0 then
halt(1);
end;
```
## Integration Scenarios
### Scenario 1: Rust Test β Pascal Validation
```
ββ Rust Test βββββββββββββββββββββββββββββββββββββββ
β 1. Create tensor β
β 2. Perform operation (SLICE/TRANSPOSE/etc) β
β 3. Export descriptor via C FFI β
β 4. Call Pascal validator β
β 5. Compare result β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Export TTensorDescriptor
ββ Pascal Validator βββββββββββββββββββββββββββββββββ
β ValidateXxx(descriptor, buffer) β
β VerifyGovernanceLemmas(descriptor, buffer) β
β β Returns TTestResult or TTestReport β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Result
ββ Assertion ββββββββββββββββββββββββββββββββββββββββ
β Expected == Actual? β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
### Scenario 2: CI/CD Integration
```bash
#!/bin/bash
# Build Rust implementation
cd tensor-core/nraay-tensor
cargo build --tests
# Build Pascal reference
cd ../../pascal
make build
# Run Rust tests with Pascal validator
cd ../tensor-core/nraay-tensor
cargo test --features conformance-check
# Exit code from conformance (invokes Pascal)
exit $?
```
### Scenario 3: FFI Cross-Calling
**Rust exposes C interface:**
```rust
#[repr(C)]
pub struct CTensorDescriptor {
pub rank: u32,
pub shape_ptr: *const u32,
pub strides_ptr: *const u32,
pub offset: u32,
pub len: u32,
pub is_contiguous: u8,
pub owns_storage: u8,
pub generation: u32,
}
#[no_mangle]
pub extern "C" fn validate_descriptor(desc: *const CTensorDescriptor) -> i32 {
// Pascal side will call this
0 // success
}
```
**Pascal calls Rust validator:**
```pascal
{ In validation.pas }
function ValidateWithRust(const desc: TTensorDescriptor): TTestResult;
begin
// Call Rust validator via C FFI
if ValidateRustTensor(@desc) = 0 then
result := TEST_PASS
else
result := TEST_FAIL_UNKNOWN;
end;
```
## File Structure for Integration
```
devflow-finance-twin/
βββ tensor-core/
β βββ nraay-tensor/
β β βββ src/
β β β βββ lib.rs
β β β βββ tensor.rs
β β β βββ lemmas.rs
β β β βββ error.rs
β β βββ Cargo.toml
β βββ FORMAL_SPEC.md
β
βββ pascal/ β Reference Implementation
β βββ buffer.pas β Arc/refcount semantics
β βββ tensor_array.pas β Buffer wrapper
β βββ descriptor.pas β C-compatible metadata
β βββ ownership.pas β State machine
β βββ governance.pas β 5 lemmas
β βββ materialize.pas β COW barrier
β βββ tensor.pas β Main operations
β βββ validation.pas β Oracle functions
β βββ tests.pas β Test suite
β βββ nraay_tensor_ref.pas β Main program
β βββ Makefile
β βββ README.md
β βββ IMPLEMENTATION_SUMMARY.md
β βββ INTEGRATION_GUIDE.md β You are here
```
## API Reference for Integration
### Validation Oracles
```pascal
{ Compare descriptors }
function CompareDescriptors(const a, b: TTensorDescriptor): TTestResult;
{ Validate operations }
function ValidateAlloc(const t: TNraayTensor): TTestReport;
function ValidateSlice(const original, sliced: TNraayTensor): TTestReport;
function ValidateTranspose(const original, transposed: TNraayTensor;
const perm: array of uint32): TTestReport;
function ValidateMaterialize(const before, after: TNraayTensor): TTestReport;
function ValidateClone(const original, cloned: TNraayTensor): TTestReport;
{ Verify governance }
function VerifyGovernanceLemmas(const t: TNraayTensor;
buf: PBuffer): boolean;
{ Run all tests }
function RunAllTests: TTestStats;
```
### Core Tensor API
```pascal
{ Allocation & Deallocation }
function CreateTensor(const shape: array of uint32): TNraayTensor;
procedure DestroyTensor(var t: TNraayTensor);
{ Cloning }
function CloneTensor(const t: TNraayTensor): TNraayTensor;
{ Element Access }
function GetElement(const t: TNraayTensor;
const coord: array of uint32): single;
procedure SetElement(var t: TNraayTensor;
const coord: array of uint32; value: single);
{ Operations }
function Slice(const t: TNraayTensor;
const ranges: array of array of uint32): TNraayTensor;
function Transpose(const t: TNraayTensor;
const perm: array of uint32): TNraayTensor;
procedure Materialize(var t: TNraayTensor);
{ Queries }
function IsValid(const t: TNraayTensor): boolean;
function Length(const t: TNraayTensor): uint32;
function Rank(const t: TNraayTensor): uint32;
```
## Testing Checklists
### Pre-Integration Checklist
- [ ] Pascal code compiles without errors
- [ ] All 10 unit tests pass
- [ ] All 5 governance lemmas verified
- [ ] Makefile build succeeds
- [ ] Demo program runs successfully
- [ ] No memory leaks (valgrind/gdb if needed)
### Conformance Test Checklist
- [ ] ALLOC operation matches Rust creation
- [ ] Element get/set consistent
- [ ] SLICE creates proper views
- [ ] TRANSPOSE permutes correctly
- [ ] MATERIALIZE restores contiguity
- [ ] CLONE increments refcount
- [ ] Generation tracking monotonic
- [ ] State transitions valid
- [ ] Descriptors equivalent
- [ ] Reference counting correct
### Regression Checklist
- [ ] All previous tests still pass
- [ ] No descriptor mismatches
- [ ] Governance lemmas hold
- [ ] No generation conflicts
- [ ] Refcount semantics maintained
- [ ] Ownership state machine valid
## Debugging Tips
### Verify descriptor structure
```pascal
procedure DebugDescriptor(const desc: TTensorDescriptor);
begin
writeln('Rank: ', desc.rank);
writeln('Len: ', desc.len);
writeln('Offset: ', desc.offset);
writeln('B_layout: ', desc.is_contiguous);
writeln('B_own: ', desc.owns_storage);
writeln('Generation: ', desc.generation);
end;
```
### Check state machine
```pascal
procedure DebugOwnership(const token: TOwnershipToken);
begin
writeln('State: ', StateToString(token.state));
writeln('Generation: ', token.generation);
writeln('Refcount: ', token.refcount);
end;
```
### Validate lemmas
```pascal
procedure DebugLemmas(const t: TNraayTensor; buf: PBuffer);
var
proof: TLemmaProof;
begin
proof := ProveShapeRank(t.descriptor);
if not IsProofValid(proof) then
writeln('Lemma 1 failed: ', proof.details);
{ ... repeat for all 5 lemmas ... }
end;
```
### Trace memory
```pascal
procedure TraceAllocation;
var
arr: TTensorArray;
begin
arr := CreateTensorArray(100);
writeln('Created: refcount=', GetRefCount(arr));
writeln('Exclusively owned: ', IsExclusivelyOwned(arr));
DropTensorArray(arr);
end;
```
## Performance Considerations
### Memory Usage
- Per tensor: ~200 bytes overhead (descriptor + arrays)
- Per buffer: 4 + refcount size + allocation
- No significant overhead beyond Rust equivalent
### Compilation Time
- FPC: ~1-2 seconds (full build)
- Rust: ~30-60 seconds (comparable)
### Runtime Performance
- All operations O(1) or O(n) (matching Rust)
- No interpretation overhead
- Direct pointer arithmetic
### Profiling
```bash
# Generate flamegraph (if perf available)
fpc -g nraay_tensor_ref.pas
perf record -g ./nraay_tensor_ref
perf report
```
## Common Integration Issues
### Issue 1: Descriptor Structure Mismatch
**Symptom:** Field offsets don't match between Rust and Pascal
**Solution:** Use `#[repr(C)]` on Rust side, `{$PACKRECORDS C}` on Pascal
**Verification:** Compare sizes with sizeof()/SizeOf()
### Issue 2: Pointer Lifetime
**Symptom:** Stale pointers after materialization
**Solution:** Re-export descriptor after each mutation
**Verification:** Compare generation before/after
### Issue 3: Refcount Tracking
**Symptom:** Unexpected refcount values
**Solution:** Track all Clone/Drop operations
**Verification:** Use ValidateRefCounting() oracle
### Issue 4: Generation Overflow
**Symptom:** Generation counter wraps or causes issues
**Solution:** Use uint32 (4 billion+ generations sufficient)
**Verification:** Log generation values during operations
## Next Steps
1. **Build and test Pascal reference**
```bash
make test
```
2. **Export Rust tensor as C descriptor**
- Implement to_c_descriptor() on NraayTensor
- Ensure struct layout matches TTensorDescriptor
3. **Call Pascal validators from Rust tests**
- Link pascal library via C FFI
- Invoke oracles in test assertions
4. **Run conformance test suite**
- Compare Rust results with Pascal expectations
- Report any discrepancies
5. **Document findings**
- Record any semantic differences
- Update specs if needed
## References
- [README.md](README.md) - Architecture guide
- [IMPLEMENTATION_SUMMARY.md](IMPLEMENTATION_SUMMARY.md) - Implementation details
- [../FORMAL_SPEC.md](../FORMAL_SPEC.md) - Mathematical semantics
- [../nraay-tensor/src/lemmas.rs](../nraay-tensor/src/lemmas.rs) - Formal proofs
- [../nraay-tensor/src/tensor.rs](../nraay-tensor/src/tensor.rs) - Rust reference
## Support
For issues or questions:
1. Check IMPLEMENTATION_SUMMARY.md for known limitations
2. Review test cases for usage examples
3. Verify governance lemmas hold
4. Check generation tracking consistency
---
**Status:** Production ready for conformance testing
**Last Updated:** 2026-09-22
|