* feat: introduce hindsight-api-slim and hindsight-all-slim packages Closes #552 - Move all source code from hindsight-api/ to new hindsight-api-slim/ - hindsight-api-slim has heavy ML deps (torch, sentence-transformers, transformers, einops, flashrank, mlx, mlx-lm, safetensors) and pg0-embedded as optional extras: [local-ml], [embedded-db], [all] - hindsight-api becomes a zero-code meta-package depending on hindsight-api-slim[all] for full backward compatibility - Add hindsight-all-slim meta-package: hindsight-api-slim + client + embed - hindsight-all updated to depend on hindsight-api-slim[all] - pg0.py: lazy-import pg0 with clear ImportError pointing to [embedded-db] - Dockerfile: replace sed hack with proper uv sync --extra flags - Update release.yml, test.yml, lint.sh, release.sh, CLAUDE.md and all path references throughout the repo * refactor: rename hindsight/ directory to hindsight-all/ * docs: document hindsight-api-slim and hindsight-all-slim package variants Add package variants table and extras explanation to installation.md * docs: remove emojis from installation.md, use professional tone * docs: link Docker slim variant to pip package variants section * docs: consolidate Docker image variants into single table * ci: fix working-directory paths after package restructure - Replace all hindsight-api → hindsight-api-slim in test.yml - Replace hindsight → hindsight-all in test.yml - Add --extra embedded-db to test-embed API install step * ci: add local-ml and embedded-db extras to API sync steps These extras were previously implicit in the old hindsight-api package (which bundled everything). Now that hindsight-api-slim uses optional extras, we must explicitly request local-ml and embedded-db in CI. * ci: add API install step with embedded-db to test-embed smoke test The smoke test starts hindsight-api as a daemon, which requires pg0-embedded. Add a dedicated install step for hindsight-api-slim with embedded-db extra so the daemon can start successfully. * ci: remove --no-install-project when using optional extras When --no-install-project is combined with --extra, the optional deps are not installed because extras require the project to be active. Remove --no-install-project from steps that need local-ml or embedded-db. * ci: fix ordering of uv sync steps to preserve optional extras When uv sync runs for a different workspace member, it removes optional extras installed for other members. Fix by always running extra-requiring API sync last, after other workspace member syncs. Also remove --no-install-project from embedded-db sync in test-embed, as --no-install-project prevents optional extras from being active. * ci: add local-ml extra to test-embed API install for smoke test The smoke test starts the full API server which needs sentence-transformers for local embeddings (default provider). Add local-ml extra to the install. * ci: simplify extras with --all-extras and add slim pip smoke test - Replace explicit --extra local-ml --extra embedded-db with --all-extras for cleaner, more maintainable sync steps - Add test-pip-slim job: tests hindsight-api-slim[embedded-db] without local ML models, using Cohere for embeddings/reranking (mirrors Docker slim smoke test approach) * ci: simplify slim smoke test to health check only (mirrors Docker test)
113 lines
3.3 KiB
Python
113 lines
3.3 KiB
Python
"""
|
|
Daemon mode support for Hindsight API.
|
|
|
|
Provides idle timeout for running as a background daemon.
|
|
"""
|
|
|
|
import asyncio
|
|
import logging
|
|
import os
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Default daemon configuration
|
|
DEFAULT_DAEMON_PORT = 8888
|
|
DEFAULT_IDLE_TIMEOUT = 0 # 0 = no auto-exit (hindsight-embed passes its own timeout)
|
|
|
|
# Allow override via environment variable for profile-specific logs
|
|
DAEMON_LOG_PATH = Path(os.getenv("HINDSIGHT_API_DAEMON_LOG", str(Path.home() / ".hindsight" / "daemon.log")))
|
|
|
|
|
|
class IdleTimeoutMiddleware:
|
|
"""ASGI middleware that tracks activity and exits after idle timeout."""
|
|
|
|
def __init__(self, app, idle_timeout: int = DEFAULT_IDLE_TIMEOUT):
|
|
self.app = app
|
|
self.idle_timeout = idle_timeout
|
|
self.last_activity = time.time()
|
|
self._checker_task = None
|
|
|
|
async def __call__(self, scope, receive, send):
|
|
# Update activity timestamp on each request
|
|
self.last_activity = time.time()
|
|
await self.app(scope, receive, send)
|
|
|
|
def start_idle_checker(self):
|
|
"""Start the background task that checks for idle timeout."""
|
|
self._checker_task = asyncio.create_task(self._check_idle())
|
|
|
|
async def _check_idle(self):
|
|
"""Background task that exits the process after idle timeout."""
|
|
# If idle_timeout is 0, don't auto-exit
|
|
if self.idle_timeout <= 0:
|
|
return
|
|
|
|
while True:
|
|
await asyncio.sleep(30) # Check every 30 seconds
|
|
idle_time = time.time() - self.last_activity
|
|
if idle_time > self.idle_timeout:
|
|
logger.info(f"Idle timeout reached ({self.idle_timeout}s), shutting down daemon")
|
|
# Give a moment for any in-flight requests
|
|
await asyncio.sleep(1)
|
|
# Send SIGTERM to ourselves to trigger graceful shutdown
|
|
import signal
|
|
|
|
os.kill(os.getpid(), signal.SIGTERM)
|
|
|
|
|
|
def daemonize():
|
|
"""
|
|
Fork the current process into a background daemon.
|
|
|
|
Uses double-fork technique to properly detach from terminal.
|
|
"""
|
|
# First fork - detach from parent
|
|
try:
|
|
pid = os.fork()
|
|
if pid > 0:
|
|
sys.exit(0)
|
|
except OSError as e:
|
|
sys.stderr.write(f"fork #1 failed: {e}\n")
|
|
sys.exit(1)
|
|
|
|
# Decouple from parent environment
|
|
os.chdir("/")
|
|
os.setsid()
|
|
os.umask(0)
|
|
|
|
# Second fork - prevent zombie
|
|
pid = os.fork()
|
|
if pid > 0:
|
|
sys.exit(0)
|
|
|
|
# Redirect standard file descriptors to log file
|
|
DAEMON_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
sys.stdout.flush()
|
|
sys.stderr.flush()
|
|
|
|
# Redirect stdin to /dev/null
|
|
with open("/dev/null", "r") as devnull:
|
|
os.dup2(devnull.fileno(), sys.stdin.fileno())
|
|
|
|
# Redirect stdout/stderr to log file
|
|
log_fd = open(DAEMON_LOG_PATH, "a")
|
|
os.dup2(log_fd.fileno(), sys.stdout.fileno())
|
|
os.dup2(log_fd.fileno(), sys.stderr.fileno())
|
|
|
|
|
|
def check_daemon_running(port: int = DEFAULT_DAEMON_PORT) -> bool:
|
|
"""Check if a daemon is running and responsive on the given port."""
|
|
import socket
|
|
|
|
try:
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
sock.settimeout(1)
|
|
result = sock.connect_ex(("127.0.0.1", port))
|
|
sock.close()
|
|
return result == 0
|
|
except Exception:
|
|
return False
|