keithproject commited on
Commit
36f3df7
·
1 Parent(s): 8ce5c60

feat: affine-style persistence — PGDATA directly on /data, drop sync/backup loop

Browse files

- No restore-rsync, no pg_basebackup loop (both hammered FUSE until it died)
- Per-boot FUSE repair: purge .git/ from object-store dirs, recreate empty
runtime dirs, pg_tblspc symlink to tmpfs
- First-boot DB setup gated behind FRESH_INIT flag

Files changed (3) hide show
  1. README.md +2 -3
  2. entrypoint.sh +66 -130
  3. supervisord.conf +2 -2
README.md CHANGED
@@ -91,9 +91,8 @@ docker compose up -d
91
 
92
  ## Data Persistence
93
 
94
- - **PostgreSQL**: `/data/pgdata` → mapped to `mem0_data` volume
95
- - **Request logs**: `/opt/data/history` → mapped to `mem0_history` volume
96
- - **Backup/Restore**: Automatic sync to/from `/data` on startup/shutdown
97
 
98
  ## Development
99
 
 
91
 
92
  ## Data Persistence
93
 
94
+ - **PostgreSQL**: `/data/pgdata` — cluster lives directly on the HF persistent volume (no sync/backup loop; FUSE-safe boot repair for empty dirs, `.git/` injection, and `pg_tblspc` symlink)
95
+ - **Request logs**: `/opt/data/history` (ephemeral; survives restarts only while the container lives)
 
96
 
97
  ## Development
98
 
entrypoint.sh CHANGED
@@ -7,11 +7,15 @@ echo "[entrypoint] mem0 Self-Hosted on HuggingFace Spaces"
7
  echo "==============================================================================="
8
 
9
  # ── Configuration ───────────────────────────────────────────────────────────
10
- MEM0_WORK="/opt/data" # Fast local filesystem (working dir)
11
- MEM0_BACKUP="/data" # HF mounted bucket (backup only)
 
 
 
 
 
12
  MEM0_UID=1000
13
  MEM0_GID=1000
14
- SYNC_INTERVAL="${SYNC_INTERVAL:-60}" # Default: sync every 1 minute
15
 
16
  # ── Singleton guard ──────────────────────────────────────────────────────────
17
  # Hanya satu instance yang menjalankan steps. Instance duplikat (dari HF rapid-
@@ -45,97 +49,24 @@ fi
45
 
46
  exec > >(tee -a "$ENTRYPOINT_LOG") 2>&1
47
 
48
- # ── Helper: Safe Sync (EXCLUDE large/temp files) ───────────────────────────
49
- safe_sync() {
50
- local SRC="$1"
51
- local DST="$2"
52
-
53
- if [ ! -d "$SRC" ]; then
54
- echo " Source $SRC does not exist, skipping sync"
55
- return 0
56
- fi
57
-
58
- mkdir -p "$DST"
59
-
60
- echo " Syncing: $SRC -> $DST"
61
- echo " Excluding: node_modules, .cache, logs, *.tmp, *.lock, *.pid, __pycache__"
62
-
63
- rsync -a --checksum --delete \
64
- --no-owner --no-group \
65
- --exclude='node_modules' \
66
- --exclude='.cache' \
67
- --exclude='.next/cache' \
68
- --exclude='logs' \
69
- --exclude='*.log' \
70
- --exclude='*.log.*' \
71
- --exclude='*.tmp' \
72
- --exclude='*.lock' \
73
- --exclude='*.pid' \
74
- --exclude='__pycache__' \
75
- --exclude='*.pyc' \
76
- --exclude='state.db-wal' \
77
- --exclude='state.db-shm' \
78
- "$SRC/" "$DST/"
79
-
80
- echo " ✓ Sync completed"
81
- }
82
-
83
- # ── Stage 1: Restore from backup (as root, before privilege drop) ──────────
84
  if [ "$(id -u)" = "0" ]; then
85
  echo ""
86
- echo "=== 1. Restoring mem0 data from persistent storage ==="
87
-
88
- # Create working directory on fast local filesystem
89
- mkdir -p "$MEM0_WORK"/{pgdata,sessions,logs,history}
90
- mkdir -p "$MEM0_BACKUP"/{pgdata,sessions,logs,history}
91
- chown -R ${MEM0_UID}:${MEM0_GID} "$MEM0_BACKUP"
92
-
93
- # Clean up backup-loop swap leftovers from a previous crashed run
94
- rm -rf "$MEM0_BACKUP/pgdata.tmp" "$MEM0_BACKUP/pgdata.old"
95
-
96
- # Restore from backup if exists
97
- if [ -d "$MEM0_BACKUP/pgdata" ] && [ "$(ls -A $MEM0_BACKUP/pgdata 2>/dev/null | wc -l)" -gt 0 ]; then
98
- echo "Found existing PostgreSQL data in $MEM0_BACKUP/pgdata"
99
- RESTORE_START=$(date +%s)
100
- safe_sync "$MEM0_BACKUP/pgdata" "$MEM0_WORK/pgdata"
101
- # rsync cannot set mode/owner of the transfer-root dir itself: mkdir made it
102
- # 0755 and --no-owner leaves files root-owned. Postgres requires 0700 + mem0.
103
- chown -R ${MEM0_UID}:${MEM0_GID} "$MEM0_WORK/pgdata"
104
- chmod 700 "$MEM0_WORK/pgdata"
105
- RESTORE_END=$(date +%s)
106
- echo "[TIMER] Restore from backup: $((RESTORE_END - RESTORE_START))s"
107
- echo "PostgreSQL data restored"
108
- else
109
- echo "No existing backup found, will initialize fresh PostgreSQL"
110
- fi
111
-
112
- # Restore history if exists
113
- if [ -d "$MEM0_BACKUP/history" ] && [ "$(ls -A $MEM0_BACKUP/history 2>/dev/null | wc -l)" -gt 0 ]; then
114
- echo "Found existing history in $MEM0_BACKUP/history"
115
- safe_sync "$MEM0_BACKUP/history" "$MEM0_WORK/history"
116
- echo "History restored"
117
- fi
118
- fi
119
 
120
- # ── Stage 2: Initialize PostgreSQL (as root) ───────────────────────────────
121
- if [ "$(id -u)" = "0" ]; then
122
- echo ""
123
- echo "=== 2. Initializing PostgreSQL ==="
124
-
125
- PGDATA="$MEM0_WORK/pgdata"
126
- PGLOG="/var/log/postgresql/pg.log"
127
-
128
- mkdir -p /var/log/postgresql
129
- chown -R ${MEM0_UID}:${MEM0_GID} /var/log/postgresql
130
-
131
- # Initialize PostgreSQL if not already initialized
132
  if [ ! -f "$PGDATA/PG_VERSION" ]; then
133
- echo "Initializing new PostgreSQL cluster..."
134
- INIT_START=$(date +%s)
135
-
136
- # Run initdb as mem0 user
137
  gosu mem0 /usr/lib/postgresql/15/bin/initdb -D "$PGDATA" --auth=trust --encoding=UTF8 --locale=C.UTF-8
138
-
139
  # Configure PostgreSQL for local connections
140
  cat >> "$PGDATA/postgresql.conf" <<EOF
141
  listen_addresses = 'localhost'
@@ -153,9 +84,8 @@ work_mem = 4MB
153
  min_wal_size = 1GB
154
  max_wal_size = 4GB
155
  EOF
156
-
157
- # Allow local connections without password
158
- # (replication line is required by pg_basebackup in the periodic backup loop)
159
  cat > "$PGDATA/pg_hba.conf" <<EOF
160
  local all all trust
161
  host all all 127.0.0.1/32 trust
@@ -164,17 +94,53 @@ local replication all trust
164
  host replication all 127.0.0.1/32 trust
165
  host replication all ::1/128 trust
166
  EOF
167
-
168
  chown -R ${MEM0_UID}:${MEM0_GID} "$PGDATA"
169
-
170
- INIT_END=$(date +%s)
171
- echo "[TIMER] PostgreSQL init: $((INIT_END - INIT_START))s"
172
- echo "PostgreSQL initialized"
173
  else
174
- echo "PostgreSQL already initialized"
175
  fi
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
- # Start postgres temporarily to run init-db, then stop it
 
 
 
178
  echo "Running database initialization script..."
179
  PGLOG="/tmp/pg-init.log"
180
  touch "$PGLOG" && chown ${MEM0_UID}:${MEM0_GID} "$PGLOG"
@@ -202,38 +168,8 @@ EOF
202
  gosu mem0 /usr/lib/postgresql/15/bin/pg_ctl -D "$PGDATA" -w stop
203
  fi
204
 
205
- # ── Stage 3: Periodic backup loop (/opt/data → /data) ──────────────────────
206
- # ponytail: pg_basebackup gives a transactionally-consistent physical copy that
207
- # drops into the existing boot-restore path unchanged. Ceiling: data loss window
208
- # = SYNC_INTERVAL seconds; no shutdown sync (exec replaces the shell).
209
- echo ""
210
- echo "=== 3. Starting periodic backup to $MEM0_BACKUP ==="
211
- (
212
- while true; do
213
- sleep "$SYNC_INTERVAL"
214
- # Postgres: consistent physical backup via local trust connection.
215
- # Write to .tmp then atomic swap so a failed run never destroys the last good backup.
216
- if gosu mem0 /usr/lib/postgresql/15/bin/pg_basebackup \
217
- -h 127.0.0.1 -U mem0 -D "$MEM0_BACKUP/pgdata.tmp" -Fp -Xs >/dev/null 2>&1; then
218
- rm -rf "$MEM0_BACKUP/pgdata.old"
219
- [ -d "$MEM0_BACKUP/pgdata" ] && mv "$MEM0_BACKUP/pgdata" "$MEM0_BACKUP/pgdata.old"
220
- mv "$MEM0_BACKUP/pgdata.tmp" "$MEM0_BACKUP/pgdata"
221
- else
222
- echo "[backup] pg_basebackup failed — keeping previous backup"
223
- rm -rf "$MEM0_BACKUP/pgdata.tmp"
224
- fi
225
- # History DB (SQLite) + telemetry: plain rsync, safe for these files
226
- if [ -d "$MEM0_WORK/history" ]; then
227
- mkdir -p "$MEM0_BACKUP/history"
228
- rsync -a --no-owner --no-group \
229
- --exclude='*.tmp' --exclude='*.lock' --exclude='*.pid' \
230
- "$MEM0_WORK/history/" "$MEM0_BACKUP/history/"
231
- fi
232
- done
233
- ) &
234
-
235
  echo ""
236
- echo "=== 4. Starting services via supervisord ==="
237
 
238
  # Stream program logs to container stdout so tracebacks are visible in HF logs.
239
  # (supervisord itself cannot reopen /dev/fd/1 -> EACCES on every dispatcher)
 
7
  echo "==============================================================================="
8
 
9
  # ── Configuration ───────────────────────────────────────────────────────────
10
+ # Affine-style: PGDATA lives DIRECTLY on the HF persistent volume (/data).
11
+ # No restore-rsync, no backup loop — both hammered the FUSE mount until it
12
+ # died ("Transport endpoint is not connected"). FUSE quirks handled below:
13
+ # empty dirs are dropped and .git/ is injected into tracked dirs, so dirs
14
+ # Postgres scans as object stores must be purged at every boot.
15
+ MEM0_WORK="/opt/data" # Fast local FS: history, sessions, logs
16
+ PGDATA="/data/pgdata" # Persistent HF bucket (FUSE)
17
  MEM0_UID=1000
18
  MEM0_GID=1000
 
19
 
20
  # ── Singleton guard ──────────────────────────────────────────────────────────
21
  # Hanya satu instance yang menjalankan steps. Instance duplikat (dari HF rapid-
 
49
 
50
  exec > >(tee -a "$ENTRYPOINT_LOG") 2>&1
51
 
52
+ # ── Stage 1: Prepare persistent storage (as root) ───────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  if [ "$(id -u)" = "0" ]; then
54
  echo ""
55
+ echo "=== 1. Preparing persistent storage ==="
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ mkdir -p "$MEM0_WORK"/{history,sessions,logs}
58
+ mkdir -p "$PGDATA"
59
+ chown ${MEM0_UID}:${MEM0_GID} "$MEM0_WORK"/* 2>/dev/null || true
60
+ chown -R ${MEM0_UID}:${MEM0_GID} "$PGDATA"
61
+
62
+ # Init if empty
63
+ FRESH_INIT=0
 
 
 
 
 
64
  if [ ! -f "$PGDATA/PG_VERSION" ]; then
65
+ FRESH_INIT=1
66
+ echo "[entrypoint] Initializing PostgreSQL at $PGDATA"
67
+ chmod 700 "$PGDATA"
 
68
  gosu mem0 /usr/lib/postgresql/15/bin/initdb -D "$PGDATA" --auth=trust --encoding=UTF8 --locale=C.UTF-8
69
+
70
  # Configure PostgreSQL for local connections
71
  cat >> "$PGDATA/postgresql.conf" <<EOF
72
  listen_addresses = 'localhost'
 
84
  min_wal_size = 1GB
85
  max_wal_size = 4GB
86
  EOF
87
+
88
+ # Allow local connections without password (incl. replication for future use)
 
89
  cat > "$PGDATA/pg_hba.conf" <<EOF
90
  local all all trust
91
  host all all 127.0.0.1/32 trust
 
94
  host replication all 127.0.0.1/32 trust
95
  host replication all ::1/128 trust
96
  EOF
97
+
98
  chown -R ${MEM0_UID}:${MEM0_GID} "$PGDATA"
99
+ echo "[TIMER] PostgreSQL init complete"
 
 
 
100
  else
101
+ echo "PostgreSQL data exists at $PGDATA"
102
  fi
103
+
104
+ # FUSE repair, every boot (mirrors affine bootstrap.sh):
105
+ # - HF bucket drops empty dirs and injects .git/ into tracked dirs.
106
+ # - Postgres scans these dirs as object stores; any stray entry → PANIC.
107
+ # They must exist and be COMPLETELY EMPTY (no .gitkeep).
108
+ for dir in pg_replslot pg_twophase pg_dynshmem pg_notify; do
109
+ mkdir -p "$PGDATA/$dir"
110
+ find "$PGDATA/$dir" -mindepth 1 -delete 2>/dev/null || true
111
+ done
112
+ # These tolerate a .gitkeep marker (Postgres ignores unknown files here)
113
+ for dir in pg_commit_ts pg_serial pg_stat pg_stat_tmp \
114
+ pg_logical/snapshots pg_logical/mappings; do
115
+ mkdir -p "$PGDATA/$dir"
116
+ touch "$PGDATA/$dir/.gitkeep"
117
+ find "$PGDATA/$dir" -mindepth 1 -name '.git' -type d -exec rm -rf {} + 2>/dev/null || true
118
+ done
119
+ # pg_tblspc must be a symlink to tmpfs — FUSE drops real empty dirs
120
+ mkdir -p /tmp/pg_tblspc
121
+ rm -rf "$PGDATA/pg_tblspc"
122
+ ln -sfn /tmp/pg_tblspc "$PGDATA/pg_tblspc"
123
+
124
+ # Defensive re-assert: only UID 1000 persists on the FUSE idmapped mount.
125
+ # Scoped chown on dirs only — recursive chown over FUSE has killed the mount.
126
+ chown ${MEM0_UID}:${MEM0_GID} "$PGDATA" "$PGDATA"/*/ 2>/dev/null || true
127
+ chmod 700 "$PGDATA"
128
+
129
+ # Fix socket dir so mem0 can create the unix socket lock file
130
+ mkdir -p /var/run/postgresql
131
+ chown ${MEM0_UID}:${MEM0_GID} /var/run/postgresql
132
+ export FRESH_INIT
133
+ fi
134
+
135
+ # ── Stage 2: First-boot DB setup (fresh cluster only) ──────────────────────
136
+ if [ "$(id -u)" = "0" ] && [ "${FRESH_INIT:-0}" = "1" ]; then
137
+ echo ""
138
+ echo "=== 2. First-boot database setup ==="
139
 
140
+ mkdir -p /var/log/postgresql
141
+ chown -R ${MEM0_UID}:${MEM0_GID} /var/log/postgresql
142
+
143
+ # Start postgres temporarily to run init-db + migrations, then stop
144
  echo "Running database initialization script..."
145
  PGLOG="/tmp/pg-init.log"
146
  touch "$PGLOG" && chown ${MEM0_UID}:${MEM0_GID} "$PGLOG"
 
168
  gosu mem0 /usr/lib/postgresql/15/bin/pg_ctl -D "$PGDATA" -w stop
169
  fi
170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  echo ""
172
+ echo "=== 3. Starting services via supervisord ==="
173
 
174
  # Stream program logs to container stdout so tracebacks are visible in HF logs.
175
  # (supervisord itself cannot reopen /dev/fd/1 -> EACCES on every dispatcher)
supervisord.conf CHANGED
@@ -9,7 +9,7 @@ pidfile=/var/log/supervisor/supervisord.pid
9
  childlogdir=/var/log/supervisor
10
 
11
  [program:postgresql]
12
- command=/usr/lib/postgresql/15/bin/postgres -D /opt/data/pgdata -c config_file=/opt/data/pgdata/postgresql.conf
13
  user=mem0
14
  autostart=true
15
  autorestart=true
@@ -21,7 +21,7 @@ stdout_logfile_backups=5
21
  stderr_logfile=/var/log/supervisor/postgresql.err.log
22
  stderr_logfile_maxbytes=10MB
23
  stderr_logfile_backups=5
24
- environment=PGDATA="/opt/data/pgdata",PGPORT="5432"
25
 
26
  [program:mem0-api]
27
  ; file logs are streamed to container stdout by entrypoint's tail -F
 
9
  childlogdir=/var/log/supervisor
10
 
11
  [program:postgresql]
12
+ command=/usr/lib/postgresql/15/bin/postgres -D /data/pgdata -c config_file=/data/pgdata/postgresql.conf
13
  user=mem0
14
  autostart=true
15
  autorestart=true
 
21
  stderr_logfile=/var/log/supervisor/postgresql.err.log
22
  stderr_logfile_maxbytes=10MB
23
  stderr_logfile_backups=5
24
+ environment=PGDATA="/data/pgdata",PGPORT="5432"
25
 
26
  [program:mem0-api]
27
  ; file logs are streamed to container stdout by entrypoint's tail -F