embeddenator-fs 0.25.0

EmbrFS: FUSE filesystem backed by holographic engrams
Documentation
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
# FUSE Implementation Guide

**Document Version:** 1.0  
**Last Updated:** January 10, 2026  
**Target Audience:** Developers, System Administrators

## Overview

EmbrFS provides optional FUSE (Filesystem in Userspace) support for mounting holographic engrams as read-only filesystems. This allows standard Unix tools (`ls`, `cat`, `grep`, etc.) to access engram contents transparently.

## Quick Start

### Prerequisites

**Linux Requirements:**
- Linux kernel 2.6.26 or later
- FUSE library installed:
  ```bash
  # Debian/Ubuntu
  sudo apt-get install libfuse3-3 libfuse3-dev
  
  # Fedora/RHEL
  sudo dnf install fuse3 fuse3-devel
  
  # Arch Linux
  sudo pacman -S fuse3
  ```

**Permissions:**
- Root access (for mounting), OR
- User must be in `fuse` group with `user_allow_other` in `/etc/fuse.conf`

**Enable Feature Flag:**
```toml
[dependencies]
embeddenator-fs = { version = "0.20.0-alpha.3", features = ["fuse"] }
```

### Basic Mounting

```rust
use embeddenator_fs::{EmbrFS, fuse::mount_embrfs};
use std::path::Path;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load engram
    let fs = EmbrFS::load("filesystem.engram")?;
    
    // Mount as read-only filesystem
    let mountpoint = Path::new("/mnt/embrfs");
    mount_embrfs(fs, mountpoint, &[])?;
    
    Ok(())
}
```

**Command-line usage** (if CLI tool available):
```bash
# Mount engram
embrfs mount filesystem.engram /mnt/embrfs

# Unmount
fusermount -u /mnt/embrfs
# or
umount /mnt/embrfs
```

### Accessing Mounted Filesystem

Once mounted, access files normally:

```bash
# List files
ls -lah /mnt/embrfs

# Read file
cat /mnt/embrfs/file.txt

# Search
grep -r "pattern" /mnt/embrfs/

# Copy out
cp -r /mnt/embrfs/data /tmp/extracted

# Tar archive
tar czf backup.tar.gz -C /mnt/embrfs .
```

## FUSE Operations Reference

### Implemented Operations

| Operation   | Description                          | Status | Notes                          |
|-------------|--------------------------------------|--------|--------------------------------|
| `init`      | Initialize filesystem                |  Full | Called on mount               |
| `destroy`   | Cleanup on unmount                   |  Full | Called on unmount             |
| `lookup`    | Resolve filename to inode            |  Full | Path normalization applied    |
| `getattr`   | Get file/directory attributes        |  Full | Returns size, mode, timestamps|
| `read`      | Read file data                       |  Full | Supports offset and size      |
| `open`      | Open file for reading                |  Full | Read-only enforcement (O_RDONLY)|
| `release`   | Close file handle                    |  Full | Cleanup file state            |
| `opendir`   | Open directory                       |  Full | Validates directory exists    |
| `readdir`   | Read directory entries               |  Full | Includes `.` and `..`         |
| `releasedir`| Close directory handle               |  Full | Cleanup directory state       |
| `statfs`    | Get filesystem statistics            |  Full | Reports blocks, inodes        |
| `access`    | Check access permissions             |  Simplified | Basic mode checking      |
| `readlink`  | Read symbolic link target            |  ENOSYS | Symlinks not supported       |

### Not Implemented (Write Operations)

All write operations return **EROFS** (Read-Only Filesystem):

| Operation    | Why Not Implemented                                    |
|--------------|--------------------------------------------------------|
| `write`      | Engrams are immutable (by design)                      |
| `create`     | Cannot create files in immutable engram                |
| `mknod`      | Cannot create special files                            |
| `mkdir`      | Cannot create directories                              |
| `unlink`     | Cannot delete files (use API-level `remove_files`)     |
| `rmdir`      | Cannot delete directories                              |
| `rename`     | Cannot rename files                                    |
| `link`       | Hard links not supported                               |
| `symlink`    | Symbolic links not supported                           |
| `chmod`      | Permissions are immutable                              |
| `chown`      | Ownership is immutable                                 |
| `truncate`   | Cannot modify file sizes                               |
| `utimens`    | Timestamps are immutable                               |
| `flush`      | No write buffer to flush                               |
| `fsync`      | No dirty data to sync                                  |
| `setxattr`   | Extended attributes not supported                      |
| `getxattr`   | Extended attributes not supported                      |
| `listxattr`  | Extended attributes not supported                      |
| `removexattr`| Extended attributes not supported                      |

**Design Rationale:** Holographic engrams are immutable snapshots. Modifications require API-level operations (`add_files`, `modify_files`, etc.) that re-encode the engram. FUSE is for browsing, not editing.

## Implementation Details

### Inode Management

**Inode Number Assignment:**
- Root directory: inode 1
- Files/directories: Sequentially assigned from 2
- Stable across mounts (same path → same inode)

**Inode Table:**
```rust
pub struct InodeTable {
    path_to_inode: HashMap<PathBuf, u64>,
    inode_to_path: HashMap<u64, PathBuf>,
    next_inode: AtomicU64,
}
```

**Thread Safety:**
- Wrapped in `Arc<RwLock<...>>`
- Read lock for lookups (concurrent)
- Write lock for new inode assignments (rare)

### File Attributes

**Reported Attributes:**
- `st_ino` - Inode number
- `st_mode` - File type and permissions
  - Files: `0o100444` (r--r--r--)
  - Directories: `0o040555` (r-xr-xr-x)
- `st_nlink` - Hard link count (always 1)
- `st_uid` - User ID (current user)
- `st_gid` - Group ID (current group)
- `st_size` - File size in bytes
- `st_blocks` - Blocks allocated (calculated from size)
- `st_atime`, `st_mtime`, `st_ctime` - Timestamps (engram creation time)

**Limitations:**
- All files owned by mounting user (no per-file ownership)
- All files have read-only permissions (no per-file modes)
- Timestamps are engram creation time (no per-file modification times)

### Read Operation

**Implementation:**
```rust
fn read(
    &mut self,
    _req: &Request<'_>,
    ino: u64,
    fh: u64,
    offset: i64,
    size: u32,
    _flags: i32,
    _lock_owner: Option<u64>,
    reply: ReplyData,
) {
    // 1. Lookup path from inode
    // 2. Read file from engram (with offset and size)
    // 3. Return data or error
}
```

**Optimizations:**
- Partial reads supported (offset + size)
- Chunk-level caching (LRU for decoded chunks)
- Zero-copy where possible (direct buffer pass-through)

**Error Handling:**
- Invalid inode → ENOENT
- Offset beyond EOF → Empty read (0 bytes)
- Engram read error → EIO

### Directory Operations

**readdir Implementation:**
```rust
fn readdir(
    &mut self,
    _req: &Request<'_>,
    ino: u64,
    fh: u64,
    offset: i64,
    mut reply: ReplyDirectory,
) {
    // 1. Lookup directory path
    // 2. Add "." and ".." entries
    // 3. List children from manifest
    // 4. Return entries with inodes and types
}
```

**Entry Order:**
1. `.` (current directory)
2. `..` (parent directory)
3. Children (sorted alphabetically)

**Performance:**
- O(1) lookup via inverted index
- O(N) iteration over children (N = # children)
- No hierarchical traversal (flat manifest)

### Statfs (Filesystem Statistics)

**Reported Statistics:**
```rust
pub struct StatfsInfo {
    blocks: u64,      // Total blocks (engram size / block_size)
    bfree: u64,       // Free blocks (0 - read-only)
    bavail: u64,      // Available blocks (0 - read-only)
    files: u64,       // Total files (from manifest)
    ffree: u64,       // Free inodes (0 - read-only)
    bsize: u32,       // Block size (4096)
    namelen: u32,     // Max filename length (255)
    frsize: u32,      // Fragment size (4096)
}
```

**Notes:**
- `blocks` calculated from engram file size
- `bfree` and `bavail` are 0 (read-only filesystem)
- `files` counts all files in manifest
- `ffree` is 0 (no more files can be added via FUSE)

## Performance Considerations

### Benchmarks

**Read Performance:**
- Sequential read: ~100-200 MB/s (single-threaded)
- Random read: ~10-50 MB/s (depends on chunk caching)
- Small file read (<4KB): ~1-5 ms per file
- Large file read (>1MB): ~5-20 ms + data transfer time

**Directory Listing:**
- Small directory (<100 files): ~1-5 ms
- Large directory (>1000 files): ~10-50 ms
- Nested directory traversal: O(depth) × directory_list_time

**Factors:**
- Disk I/O (engram file read)
- Chunk decoding (VSA unbundling)
- Correction application (bit-perfect reconstruction)
- LRU cache hit rate

### Optimization Tips

**1. Enable LRU Caching:**
```rust
let options = MountOptions {
    cache_size: 1000,  // Cache 1000 sub-engrams
    ..Default::default()
};
```

**2. Use Hierarchical Engrams:**
- Reduces memory footprint
- Improves cache hit rate
- Faster directory listings

**3. Avoid Repeated Mounts:**
- Keep engram mounted for duration of work
- Unmounting/remounting is expensive (full reload)

**4. Batch Operations:**
- Use `rsync` or `tar` for bulk extraction
- Reduces FUSE call overhead

## Troubleshooting

### Common Issues

**1. Permission Denied on Mount**

```
Error: FUSE mount failed: Permission denied
```

**Solutions:**
- Run with `sudo`
- Add user to `fuse` group: `sudo usermod -a -G fuse $USER`
- Enable `user_allow_other` in `/etc/fuse.conf`:
  ```
  # /etc/fuse.conf
  user_allow_other
  ```
- Logout and login for group changes to take effect

**2. Device or Resource Busy**

```
Error: umount: /mnt/embrfs: target is busy
```

**Solutions:**
- Close all programs accessing mountpoint
- Check with `lsof /mnt/embrfs` or `fuser -m /mnt/embrfs`
- Force unmount: `sudo umount -l /mnt/embrfs` (lazy unmount)

**3. File Not Found (ENOENT)**

```
Error: cat: /mnt/embrfs/file.txt: No such file or directory
```

**Causes:**
- File not in engram (check with `ls -R /mnt/embrfs`)
- Path case mismatch (Linux is case-sensitive)
- File marked as deleted (soft delete in manifest)

**Debug:**
- Check manifest: `embrfs info filesystem.engram`
- Verify path: `embrfs list filesystem.engram | grep file.txt`

**4. Input/Output Error (EIO)**

```
Error: cat: /mnt/embrfs/file.txt: Input/output error
```

**Causes:**
- Corrupted engram file
- Hash verification failure (data mismatch)
- Disk read error

**Debug:**
- Verify engram integrity: `embrfs verify filesystem.engram`
- Check disk errors: `dmesg | tail`
- Re-encode engram from original source

**5. Operation Not Supported (ENOSYS)**

```
Error: readlink: /mnt/embrfs/link: Function not implemented
```

**Cause:** Symbolic links not supported in EmbrFS.

**Workaround:** Copy regular files only, skip symlinks.

### Debug Mode

**Enable FUSE debugging:**
```rust
let options = MountOptions {
    debug: true,  // Print all FUSE operations to stderr
    ..Default::default()
};
mount_embrfs(fs, mountpoint, &options)?;
```

**Output:**
```
FUSE: lookup(parent=1, name="file.txt")
FUSE: getattr(ino=42)
FUSE: open(ino=42, flags=O_RDONLY)
FUSE: read(ino=42, offset=0, size=4096)
FUSE: release(ino=42)
```

### Logging

**Enable library logging:**
```rust
env_logger::Builder::from_default_env()
    .filter_level(log::LevelFilter::Debug)
    .init();
```

**Environment variable:**
```bash
RUST_LOG=embeddenator_fs=debug embrfs mount filesystem.engram /mnt/embrfs
```

## Advanced Usage

### Mount Options

```rust
pub struct MountOptions {
    pub debug: bool,           // Enable FUSE debug output
    pub auto_unmount: bool,    // Unmount on process exit
    pub allow_root: bool,      // Allow root to access filesystem
    pub allow_other: bool,     // Allow all users to access filesystem
    pub cache_size: usize,     // LRU cache size for sub-engrams
    pub read_only: bool,       // Force read-only (redundant, always true)
}
```

**Example:**
```rust
let options = MountOptions {
    debug: false,
    auto_unmount: true,
    allow_root: false,
    allow_other: true,         // Requires user_allow_other in fuse.conf
    cache_size: 500,
    read_only: true,
};

mount_embrfs(fs, mountpoint, &options)?;
```

### Programmatic Unmount

```rust
use embeddenator_fs::fuse::unmount_embrfs;

// Unmount filesystem
unmount_embrfs(Path::new("/mnt/embrfs"))?;
```

**Note:** Unmounting may fail if filesystem is busy (files open, processes in directory).

### Background Mounting

```rust
use std::thread;

let fs = EmbrFS::load("filesystem.engram")?;
let mountpoint = Path::new("/mnt/embrfs");

// Mount in background thread
let handle = thread::spawn(move || {
    mount_embrfs(fs, mountpoint, &[]).expect("Mount failed");
});

// Do work while mounted
// ...

// Wait for unmount
handle.join().unwrap();
```

### Integration with systemd

**Create systemd service:**
```ini
# /etc/systemd/system/embrfs@.service
[Unit]
Description=EmbrFS Mount for %I
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/bin/embrfs mount /data/%i.engram /mnt/%i
ExecStop=/bin/fusermount -u /mnt/%i
Restart=on-failure
User=embrfs

[Install]
WantedBy=multi-user.target
```

**Usage:**
```bash
# Enable and start
sudo systemctl enable embrfs@filesystem
sudo systemctl start embrfs@filesystem

# Check status
sudo systemctl status embrfs@filesystem

# Stop and disable
sudo systemctl stop embrfs@filesystem
sudo systemctl disable embrfs@filesystem
```

## Security Considerations

### Attack Surface

**Read-Only Nature:**
-  No write-based attacks (EROFS for all write operations)
-  No file creation/deletion
-  No permission changes

**Path Traversal:**
-  Mitigated by path normalization
-  All paths resolved relative to engram root
-  No `../..` escape possible

**Resource Exhaustion:**
-  Large engrams can consume memory (use hierarchical mode)
-  Repeated reads without caching can be slow (enable LRU cache)
-  No amplification attacks (output bounded by engram size)

### Recommendations

**Production Deployments:**
1. Mount with `allow_other=false` (default) to restrict access to mounting user
2. Use dedicated user for EmbrFS mounts (e.g., `embrfs` user)
3. Set restrictive permissions on engram files (0600)
4. Monitor for excessive FUSE operations (rate limiting)
5. Use hierarchical engrams to bound memory usage

**Untrusted Engrams:**
1. Verify hash before mounting: `embrfs verify untrusted.engram`
2. Mount in isolated namespace (container, VM)
3. Limit resources (ulimit, cgroups)
4. Scan extracted files with antivirus before use

**Network Exposure:**
-  Do NOT expose FUSE mountpoints over NFS or CIFS (performance issues)
-  Use API-level access for network sharing
-  Consider read-only HTTP server for web access

## Platform Support

| Platform        | FUSE Support | Status | Notes                          |
|-----------------|--------------|--------|--------------------------------|
| Linux           |  libfuse3  | Full   | Primary target, well-tested    |
| macOS           |  OSXFUSE   | Untested | Should work, not verified     |
| Windows         |  WinFsp    | No     | Future work, requires porting  |
| FreeBSD         |  fusefs    | Untested | Should work, not verified     |

**Recommendations:**
- **Linux:** Use libfuse3 (recommended)
- **macOS:** Install OSXFUSE, test thoroughly before production use
- **Windows:** Not supported, use API-level extraction instead

## Alternatives to FUSE

If FUSE is not available or suitable:

**1. API-Level Extraction:**
```rust
let fs = EmbrFS::load("filesystem.engram")?;
fs.extract_all("/output/dir")?;
```

**2. HTTP Server:**
```rust
// Pseudo-code for future HTTP server
let fs = EmbrFS::load("filesystem.engram")?;
let server = HttpServer::new(fs);
server.listen("0.0.0.0:8080")?;
```

**3. Archive Conversion:**
```bash
# Extract to tar (via FUSE)
embrfs mount filesystem.engram /mnt/embrfs
tar czf filesystem.tar.gz -C /mnt/embrfs .
fusermount -u /mnt/embrfs

# Or direct API (future feature)
embrfs export filesystem.engram --format tar.gz --output filesystem.tar.gz
```

## Future Enhancements

**Planned Features:**
- Copy-on-write support (immutable history)
- Overlay mode (mount engram + writable overlay)
- Snapshot browsing (mount specific engram version)
- Network filesystem support (custom protocol)

**Non-Goals:**
- Writable FUSE operations (conflicts with immutability)
- POSIX full compliance (simplified model by design)
- High-performance databases (not target use case)

## References

- [FUSE Documentation]https://www.kernel.org/doc/html/latest/filesystems/fuse.html
- [libfuse GitHub]https://github.com/libfuse/libfuse
- [fuser crate]https://docs.rs/fuser/ - Rust FUSE bindings used by EmbrFS
- [Writing a FUSE Filesystem]https://www.cs.hmc.edu/~geoff/classes/hmc.cs135.201001/homework/fuse/fuse_doc.html

---

**Document Maintenance:**
- Update after FUSE API changes
- Add benchmark results from real-world usage
- Document known bugs and workarounds