Extracted Entities Restart
🆕 What’s New - Restart Endpoint
This story has been updated to include a new REST API endpoint for manually restarting extractions:
Endpoint: POST /v1/extracted_entities/restart
Key Features:
-
Accept array of
extractedEntityIds(1-100 items) -
Query
ExtractedEntitiesJOINDocumentsto retrieve document hashes -
Send messages to Fluxx Pub/Sub with document hashes for re-extraction
-
Return detailed response with request tracking ID and errors
-
Support partial success (some entities succeed, others fail)
-
No database updates required (read-only operation)
Use Cases:
-
Operators manually restart failed extractions via API
-
Batch restart multiple extractions at once (up to 100)
-
Support for monitoring/alerting systems to auto-restart
-
Clear audit trail of who initiated restarts and why
Business Value
-
Automated Retry: Enable automatic re-extraction of failed document processing without manual intervention
-
Batch Processing: Support batch retry operations for multiple files simultaneously
-
Manual Restart: Allow operators to manually restart extraction for specific extracted entities via REST API
-
Decoupled Architecture: Stage mapper service remains decoupled from extraction service through message-based communication
-
Reliability: Failed extractions can be retried without data loss or manual file resubmission
-
Audit Trail: All retry requests are logged and traceable through Azure Service Bus
-
Scalability: Message-based architecture scales horizontally with processing demands
-
Status Tracking: Clear visibility into extraction restart status through entity status updates
Current State
Existing Architecture
The web-api-documents-ai service currently:
-
Processes documents through a stage mapper that coordinates extraction workflow
-
Has no automated mechanism to trigger re-extraction of files
-
Requires manual intervention or API calls to retry failed extractions
-
Lacks integration with Azure Service Bus messaging infrastructure
Gap Analysis
-
No pub/sub messaging infrastructure in place
-
No message publishing capability from stage mapper
-
No subscription handler to receive and process retry requests
-
No environment configuration for Service Bus topics and subscriptions
-
No structured message format for extraction retry events
Future State
Architecture Pattern
Implement Azure Service Bus pub/sub messaging following the pattern established in fluxx-file-intake:
Message Flow
-
Trigger: Stage mapper detects extraction failure or receives retry request
-
Publish: Stage mapper publishes
ExtractionRetryEventtoextraction-retrytopic -
Queue: Azure Service Bus queues message in subscription
-
Subscribe: Extraction service receives message from subscription
-
Process: Extraction handler processes retry request and re-extracts file(s)
-
Complete: Message is completed upon successful processing or abandoned for retry
Design
Message Types
ExtractionRetryEvent
This event is published to the Fluxx Pub/Sub queue to trigger extraction.
Important: The fileIds field contains document hashes (from the Documents.DocumentHash column), not database IDs. Fluxx uses these file hashes to identify and process the documents.
Message Flow for Restart Endpoint:
-
Receive
extractedEntityIdsfrom API request -
Query
ExtractedEntitiesJOINDocumentsto get document hashes (read-only) -
Send
ExtractionRetryEventwith document hashes infileIdsfield -
Fluxx receives message and initiates extraction for each file hash
-
Fluxx processes the documents and updates status accordingly
ExtractionRetryResult (Response Event)
Database Requirements
Note: The restart endpoint is read-only for the database. No status updates or database modifications are performed.
Table Relationships
Query Pattern (Read-Only):
The endpoint only reads data to retrieve document hashes. No UPDATE, INSERT, or DELETE operations are performed.
Component Architecture
1. Publisher Infrastructure
File: src/services/messaging/createServiceBusPublisher.ts
File: src/services/messaging/createSendToExtractionRetryTopic.ts
File: src/services/messaging/sendExtractionRetryEvent.ts
File: src/services/messaging/formatRetryMessage.ts
2. Subscriber Infrastructure
File: src/subscriptions/extractionRetryHandler.ts
3. Message Receiver Integration
File: src/services/topicService.ts (Update existing)
4. Stage Mapper Integration
File: src/services/stageMapper.ts (Update existing)
Phase 3: REST API Endpoint for Extraction Restart
Task 3.1: Add REST Endpoint Schema
File: src/api/v1/extractedEntity/extractedEntities.schema.ts
Add new schema for restart endpoint:
Task 3.2: Add Service Types
File: src/api/v1/extractedEntity/extractedEntities.types.ts
Add new types for restart functionality:
Task 3.3: Add Model Methods
File: src/api/v1/extractedEntity/extractedEntities.model.ts
Add method to get entities with document information:
Task 3.4: Add Service Method
File: src/api/v1/extractedEntity/extractedEntities.service.ts
Add restart extraction service method:
Task 3.5: Add Controller Method
File: src/api/v1/extractedEntity/extractedEntities.controller.ts
Add restart extraction controller method:
Task 3.6: Add Route
File: src/api/v1/extractedEntity/extractedEntities.route.ts
Add restart endpoint route:
Phase 4: Testing
Test 4.1: Unit Test - Model Methods
File: test/unit/api/v1/extractedEntity/extractedEntities.model.test.ts
Test 4.2: Unit Test - Service Method
File: test/unit/api/v1/extractedEntity/extractedEntities.service.test.ts
Test 4.3: Integration Test - Restart Endpoint
File: test/integration/extractedEntities.restart.test.ts
Implementation Steps
Phase 1: Infrastructure Setup
Task 1.1: Add Environment Configuration
File: src/constants/configuration.ts
Task 1.2: Add Environment Variables
File: .env.local.example
Required Environment Variables:
AZURE_SERVICE_BUS_CONNECTION_STRING(Required): Connection string for Azure Service Bus namespace
- Format: Endpoint=sb://<namespace>.servicebus.windows.net/;SharedAccessKeyName=<key-name>;SharedAccessKey=<key-value>
- Development: Can use local emulator with UseDevelopmentEmulator=true
-
TOPIC_EXTRACTION_RETRY(Required): Name of the topic for extraction retry events (e.g., “extraction-retry”) -
TOPIC_EXTRACTION_RESULT(Required): Name of the topic for extraction results (e.g., “extraction-result”) -
SUBSCRIPTION_EXTRACTION_RETRY(Required): Name of subscription for retry handler (e.g., “extractor-retry-subscription”) -
SUBSCRIPTION_EXTRACTION_RESULT(Optional): Name of subscription for result handler (e.g., “mapper-result-subscription”)
Task 1.3: Define Message Types
File: src/types/messaging.ts
Task 1.4: Create Publisher Infrastructure
Create the following files:
-
src/internal/pubsub/createPublisher.ts(from fluxx-file-intake pattern) -
src/internal/pubsub/createMessageSender.ts(from fluxx-file-intake pattern) -
src/internal/pubsub/createServiceBusClient.ts(from fluxx-file-intake pattern) -
src/services/messaging/createServiceBusPublisher.ts -
src/services/messaging/createSendToExtractionRetryTopic.ts -
src/services/messaging/formatRetryMessage.ts -
src/services/messaging/sendExtractionRetryEvent.ts
Task 1.5: Create Subscriber Infrastructure
Create the following files:
-
src/subscriptions/extractionRetryHandler.ts -
src/subscriptions/messageReceiver.ts(from fluxx-file-intake pattern) -
src/services/topicService.ts
Phase 2: Integration
Task 2.1: Update Stage Mapper
Add retry methods to StageMapper class:
Task 2.2: Initialize Message Receiver
File: src/index.ts (Update existing)
Task 2.3: Add API Endpoints (Optional)
File: src/routes/v1/retry.ts
Testing Strategy
Unit Tests
Test 1: Message Formatting
File: test/unit/services/messaging/formatRetryMessage.test.ts
Test 2: Send Retry Event
File: test/unit/services/messaging/sendExtractionRetryEvent.test.ts
Test 3: Extraction Retry Handler
File: test/unit/subscriptions/extractionRetryHandler.test.ts
Test 4: Stage Mapper Retry Methods
File: test/unit/services/stageMapper.test.ts
Contract Tests
Test 5: Service Bus Publish
File: test/contract/servicebus-publish.test.ts
Test 6: Service Bus Subscribe
File: test/contract/servicebus-subscribe.test.ts
Integration Tests
Test 7: End-to-End Message Flow
File: test/integration/extraction-retry-flow.test.ts
Acceptance Criteria
Functional Requirements - Restart Endpoint
-
REST API endpoint
POST /v1/extracted_entities/restartis implemented -
Endpoint accepts array of extracted entity IDs (1-100 items)
-
Endpoint accepts optional reason parameter for restart
-
Endpoint validates all entity IDs exist in database
-
Endpoint retrieves document hash for each entity via Documents table join (read-only)
-
Endpoint sends extraction retry message to Fluxx Pub/Sub with file hashes
-
Endpoint returns unique request ID for tracking
-
Endpoint returns list of file hashes sent to Fluxx
-
Endpoint returns partial success status when some entities fail validation
-
Endpoint does not modify database (read-only operation)
-
Endpoint prevents restart of entities currently in ‘processing’ status
-
Endpoint requires authentication and authorization (EXTRACTED_ENTITIES_WRITE scope)
-
Endpoint returns 400 for invalid input (empty array, >100 items)
-
Endpoint returns 404 when entities not found
-
Endpoint returns 500 for internal errors with proper logging
Functional Requirements - Message Publishing
-
Stage mapper can publish retry message for single file
-
Stage mapper can publish retry message for batch of files
-
Extraction retry handler receives and processes messages from topic
-
Retry handler validates message structure (fileIds, requestId required)
-
Retry handler enforces maximum retry attempt limit
-
Retry handler processes each file in batch independently
-
Partial failures in batch are handled gracefully
-
Success and failure results are published to result topic
-
All retry operations are logged with request context
-
Message receiver can be started and stopped cleanly
Technical Requirements - Restart Endpoint
-
Schema defined in
extractedEntities.schema.tswith proper validation -
Types defined in
extractedEntities.types.ts(RestartExtractionRequest, RestartExtractionResponse, ExtractedEntityWithDocument) -
Model methods added:
getEntitiesWithDocumentsByIds()(read-only) -
Service method added:
restartExtraction()with full business logic -
Controller method added:
restartExtraction()with proper error handling -
Route added with authentication and authorization middleware
-
No database writes performed (read-only operation)
-
Proper SQL joins for read queries between ExtractedEntities and Documents tables
-
Parameterized SQL queries to prevent SQL injection
-
Error handling for message sending
Technical Requirements - Message Infrastructure
-
Environment variables defined for Service Bus connection and topics
-
ExtractionRetryEventmessage type defined -
ExtractionRetryResultmessage type defined -
Publisher infrastructure created (createServiceBusPublisher, etc.)
-
Subscriber infrastructure created (ExtractionRetryHandler, MessageReceiver)
-
TopicService configured with retry handler
-
Message receiver initialized in application startup
-
Error handling for missing or malformed messages
-
TypeScript type safety for all message operations
Code Quality Requirements
-
All message publishing uses framework logger
-
Structured logging includes request context (requestId, fileIds, etc.)
-
No sensitive data logged in messages
-
Consistent error messages for validation failures
-
Proper async/await usage throughout
-
Message formatting consistent with existing patterns
-
Code follows existing architectural patterns from fluxx-file-intake
-
No use of
anytype without documentation -
SOLID principles followed in service and controller design
-
Repository pattern used for data access
Testing Requirements - Restart Endpoint
-
Unit test: Model.getEntitiesWithDocumentsByIds() returns correct data (read-only)
-
Unit test: Service.restartExtraction() successfully sends messages for valid entities
-
Unit test: Service.restartExtraction() handles entities not found
-
Unit test: Service.restartExtraction() rejects currently processing entities
-
Unit test: Service.restartExtraction() handles partial failures
-
Unit test: Service.restartExtraction() handles message send failure
-
Unit test: Service.restartExtraction() rejects >100 entities
-
Unit test: Controller.restartExtraction() calls service correctly
-
Integration test: POST /restart returns 200 for valid request
-
Integration test: POST /restart returns 400 for invalid request
-
Integration test: POST /restart returns proper response structure
-
Integration test: POST /restart requires authentication
-
Integration test: POST /restart requires correct scope
Testing Requirements - Message Infrastructure
-
Unit test: formatRetryMessage correctly formats timestamps
-
Unit test: sendExtractionRetryEvent publishes to correct topic
-
Unit test: ExtractionRetryHandler processes single file
-
Unit test: ExtractionRetryHandler processes batch of files
-
Unit test: ExtractionRetryHandler handles partial failures
-
Unit test: ExtractionRetryHandler validates required fields
-
Unit test: ExtractionRetryHandler enforces retry limit
-
Unit test: StageMapper.retryExtraction sends correct message
-
Unit test: StageMapper.retryExtractionBatch handles batch
-
Unit test: StageMapper.retryExtractionBatch rejects empty batch
-
Contract test: Can publish to extraction-retry topic
-
Contract test: Can subscribe to extraction-retry subscription
-
Integration test: End-to-end message flow works
-
All tests pass in CI/CD pipeline
-
Test coverage > 85% for new messaging modules and restart endpoint
Documentation Requirements
-
Environment variables documented in .env.local.example
-
README updated with Service Bus configuration instructions
-
Message types documented with JSDoc comments
-
Retry flow diagram included in documentation
-
API endpoints documented (if implemented)
-
Team training materials created
Deployment Requirements
-
Azure Service Bus namespace created in all environments
-
Topics created: extraction-retry, extraction-result
-
Subscriptions created with correct configuration
-
Environment variables configured in all environments
-
Connection strings stored securely in Azure Key Vault
-
Application successfully starts with message receiver
-
Messages flow through system in production
-
Monitoring and alerting configured for Service Bus
-
Rollback plan documented
Environment Variables Reference
Required Variables
| Variable | Description | Example | Required |
|----------|-------------|---------|----------|
| AZURE_SERVICE_BUS_CONNECTION_STRING | Connection string for Azure Service Bus namespace | Endpoint=sb://myapp.servicebus.windows.net/;... | Yes |
| TOPIC_EXTRACTION_RETRY | Name of topic for extraction retry events | extraction-retry | Yes |
| TOPIC_EXTRACTION_RESULT | Name of topic for extraction result events | extraction-result | Yes |
| SUBSCRIPTION_EXTRACTION_RETRY | Name of subscription for retry handler | extractor-retry-subscription | Yes |
| SUBSCRIPTION_EXTRACTION_RESULT | Name of subscription for result handler | mapper-result-subscription | Optional |
Development Environment
Production Environment
Azure Service Bus Configuration
-
Topic TTL: 7 days (configurable)
-
Max Delivery Count: 10 (configurable)
-
Lock Duration: 5 minutes
-
Duplicate Detection: Enabled (1 minute window)
-
Dead Letter Queue: Enabled
Non-Functional Requirements
Performance
-
Message publishing should complete in < 100ms
-
Message processing should handle 100+ messages/second
-
Batch operations should support up to 100 files per request
-
No blocking operations during message handling
Reliability
-
Messages should be delivered at-least-once
-
Failed messages should be retried automatically
-
Dead letter queue for messages exceeding max retries
-
Graceful degradation if Service Bus unavailable
Observability
-
All message operations logged with structured context
-
Request IDs preserved across async operations
-
Azure Application Insights integration
-
Service Bus metrics monitored (queue length, processing time)
Security
-
Connection strings stored in Azure Key Vault
-
Messages do not contain sensitive data (PII, credentials)
-
RBAC configured for Service Bus access
-
Network security rules configured
Risks and Mitigation
Risk 1: Message Processing Failures
Impact: High - Messages lost or stuck in queue
Mitigation:
-
Implement dead letter queue handling
-
Configure max delivery count
-
Monitor dead letter queue size
-
Alert on processing failures
Risk 2: Service Bus Unavailability
Impact: High - Cannot publish or process messages
Mitigation:
-
Implement retry logic with exponential backoff
-
Cache messages locally if Service Bus down
-
Graceful degradation for non-critical operations
-
Monitor Service Bus health
Risk 3: Duplicate Message Processing
Impact: Medium - Files extracted multiple times
Mitigation:
-
Enable duplicate detection on Service Bus
-
Implement idempotent extraction logic
-
Check file state before processing
-
Use request ID for deduplication
Risk 4: Batch Processing Failures
Impact: Medium - Partial batch failures
Mitigation:
-
Process files independently in batch
-
Track success/failure per file
-
Publish detailed result messages
-
Support retry of failed files only
Rollout Plan
Phase 1: Infrastructure Setup (Week 1)
-
Create Azure Service Bus namespace (Dev environment)
-
Create topics and subscriptions
-
Configure connection strings
-
Implement publisher infrastructure
-
Implement subscriber infrastructure
-
Update database schema to support ‘restarting’ status
-
Deploy to Dev environment
Phase 2: Message Integration (Week 2)
-
Integrate with StageMapper
-
Integrate with ExtractionService
-
Add unit tests for messaging
-
Add contract tests
-
Deploy to QA environment
Phase 3: REST API Implementation (Week 2-3)
- Implement POST /extracted_entities/restart endpoint
- Add schema, types, model methods
- Add service and controller methods
- Add route with authentication
-
Add comprehensive unit tests for endpoint
-
Add integration tests for endpoint
-
Test end-to-end flow: API → Status Update → Message → Fluxx
-
Deploy to QA environment
Phase 4: Testing (Week 3)
-
End-to-end testing in QA
-
Performance testing (message publishing)
-
Load testing (batch operations with 100 entities)
-
Chaos testing (Service Bus failures, rollback scenarios)
-
User acceptance testing of restart endpoint
-
Deploy to UAT environment
Phase 5: Production Deployment (Week 4)
-
Create production Service Bus resources
-
Configure production environment variables
-
Deploy database schema changes to production
-
Deploy to production with feature flag
-
Monitor message flow and endpoint usage
-
Enable for all users
-
Post-deployment validation
API Usage Examples
Example 1: Restart Single Extraction
Response (200 OK):
Example 2: Restart Multiple Extractions (Batch)
Response (200 OK):
Example 3: Partial Success (Some Entities Not Found)
Response (200 OK):
Example 4: Cannot Restart Processing Entity
Response (200 OK):
Example 5: Invalid Request - Empty Array
Response (400 Bad Request):
Example 6: Invalid Request - Too Many Entities
Response (400 Bad Request):
Success Metrics
Technical Metrics - Messaging
-
99.9% message delivery success rate
-
< 100ms average message publishing latency
-
< 5 seconds average message processing time
-
Zero message loss
-
< 0.1% messages in dead letter queue
Technical Metrics - REST API
-
< 500ms average response time for restart endpoint
-
99.5% success rate for valid requests
-
Proper status code usage (200, 400, 404, 500)
-
Zero data inconsistencies (status updates + messages)
-
Database transaction rollback works correctly on failures
Business Metrics
-
Automated retry reduces manual intervention by 80%
-
Failed extractions resolved within 5 minutes
-
Batch operations support up to 100 entities efficiently
-
Mean time to retry reduced from 30min to 5min
-
Operators can restart extractions via API without database access
Operational Metrics
-
Service Bus uptime > 99.9%
-
All retry requests tracked and logged
-
Zero production incidents from messaging or restart endpoint
-
Monitoring dashboards fully configured
-
Clear audit trail for all restart operations
Related Documentation
Story Points: 21
Complexity: High
Effort: 5 weeks
Dependencies: Azure Service Bus, framework-nodejs-extensions, fluxx-file-intake patterns
Additional Scope: REST API endpoint for extraction restart with batch support
Definition of Done
-
All acceptance criteria met
-
All functional requirements implemented (messaging + REST API)
-
All technical requirements completed
-
All tests passing (unit, contract, integration) with >85% coverage
-
POST /extracted_entities/restart endpoint fully implemented
-
No database writes performed (read-only operation)
-
Extracted entities correctly linked to document hashes via JOIN
-
Message sending handled with proper error handling
-
Code reviewed and approved
-
Environment variables configured in all environments
-
Azure Service Bus resources created
-
Deployed to all environments (Dev, QA, UAT, Prod)
-
API documentation complete with examples
-
OpenAPI spec updated for restart endpoint
-
Team training completed
-
Messages flowing correctly to Fluxx in production
-
Restart endpoint functioning in production
-
Monitoring configured for both messaging and endpoint
-
Post-deployment validation successful
-
Stakeholder sign-off received