Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@ OPENROUTER_API_KEY=
OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
# Choose an OpenRouter model that supports streaming and tool calling.
OPENROUTER_CHAT_MODEL=openai/gpt-4o-mini
# Ask ApplyWell limits (all providers). 0 disables a single limit; see docs/assistant-quota.md.
APP_ASSISTANT_MAX_OUTPUT_TOKENS=1024
APP_ASSISTANT_MAX_TOOL_CALLS=8
APP_ASSISTANT_QUOTA_ENABLED=true
APP_ASSISTANT_QUOTA_DAILY_LIMIT=30
APP_ASSISTANT_QUOTA_RESET_ZONE=America/Sao_Paulo
APP_ASSISTANT_QUOTA_RATE_LIMIT=5
APP_ASSISTANT_QUOTA_RATE_WINDOW=1m
APP_ASSISTANT_QUOTA_MAX_CONCURRENT=1
APP_ASSISTANT_QUOTA_GLOBAL_DAILY_LIMIT=500
APP_ASSISTANT_QUOTA_GLOBAL_RATE_LIMIT=20
APP_ASSISTANT_QUOTA_GLOBAL_RATE_WINDOW=1m

OPENAI_GPT_CLIENT_ID=
OPENAI_GPT_CLIENT_SECRET=
Expand Down
5 changes: 5 additions & 0 deletions docs/ask-applywell-backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ Events:
- `complete`: `{"sources":["APPLICATION_STATS"]}`
- `error`: a sanitized provider failure

Per-user daily quota, rate limit, single in-flight generation and global provider limits are
enforced before the provider is called. Rejections return HTTP 429 before the stream opens.
`GET /api/v1/assistant/usage` returns the caller's daily usage. See
[assistant-quota.md](assistant-quota.md).

Enable with `APP_ASSISTANT_ENABLED=true`, set `OPENAI_API_KEY`, and optionally set
`OPENAI_CHAT_MODEL`. The feature is disabled by default. Every tool is read-only and binds
the user ID captured from the authenticated request; the model never receives a user ID.
Expand Down
3 changes: 3 additions & 0 deletions docs/assistant-providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ To disable the assistant, set `APP_ASSISTANT_ENABLED=false` and
`APP_ASSISTANT_PROVIDER=none`. API keys are server-side secrets: do not
commit real values or expose them to the frontend.

Quotas, rate limits, output-token and tool-call caps apply to every provider the
same way. See [assistant-quota.md](assistant-quota.md).

There is no automatic provider fallback: selecting a provider switches
the backend on restart. OpenRouter's own provider routing and retry
behavior are separate from this selection.
115 changes: 115 additions & 0 deletions docs/assistant-quota.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# Ask ApplyWell: quotas and anti-flood

Every `POST /api/v1/assistant/chat` request goes through `AssistantQuotaService` **before** a
`ChatModel` is called. The checks live above Spring AI's `ChatModel` abstraction, so they apply
to any configured provider (OpenRouter, Gemini or a future one) without provider-specific code.

## Limits

Configure them in the server `.env` (or deployment environment) and restart the backend.
A value of `0` disables that single check.

| Variable | Default | Meaning |
| --- | --- | --- |
| `APP_ASSISTANT_QUOTA_ENABLED` | `true` | Master switch for all checks below. |
| `APP_ASSISTANT_QUOTA_DAILY_LIMIT` | `30` | Messages per user per day. |
| `APP_ASSISTANT_QUOTA_RESET_ZONE` | `America/Sao_Paulo` | Daily reset happens at local midnight in this IANA zone. It is unrelated to the provider's own reset (Gemini resets at midnight Pacific time). |
| `APP_ASSISTANT_QUOTA_RATE_LIMIT` | `5` | Messages per user in the short window. |
| `APP_ASSISTANT_QUOTA_RATE_WINDOW` | `1m` | Short (sliding) window length. |
| `APP_ASSISTANT_QUOTA_MAX_CONCURRENT` | `1` | Generations in progress per user, across all tabs, devices and instances. |
| `APP_ASSISTANT_QUOTA_GLOBAL_DAILY_LIMIT` | `500` | Provider calls per day for all users together. |
| `APP_ASSISTANT_QUOTA_GLOBAL_RATE_LIMIT` | `20` | Provider calls in the global window for all users together. |
| `APP_ASSISTANT_QUOTA_GLOBAL_RATE_WINDOW` | `1m` | Global window length. |
| `APP_ASSISTANT_QUOTA_RETENTION` | `7d` | How long request rows are kept (minimum 2 days). |
| `APP_ASSISTANT_MAX_OUTPUT_TOKENS` | `1024` | Output cap per provider call, sent as Spring AI's portable `maxTokens`. `0` keeps the provider default. |
| `APP_ASSISTANT_MAX_TOOL_CALLS` | `8` | Tool calls per message. After the budget, tools return an error and the model must answer with what it has. `0` means unlimited. |
| `APP_ASSISTANT_MAX_MESSAGE_LENGTH` | `4000` | Prompt size cap (existing). Conversation memory is capped at 20 messages. |

Set the global limits **below** your provider plan (OpenRouter key/model limits or Gemini
project RPM/RPD). A single message can trigger several provider round-trips when the model
uses tools, so the real provider request count can be up to `1 + APP_ASSISTANT_MAX_TOOL_CALLS`
per message. Keep a margin.

## How it stays correct

- Each authorized request inserts a row in `assistant_request_reservations`. Checks and the
insert run in one transaction that first locks the `assistant_quota_locks` row
(`SELECT ... FOR UPDATE`, `READ COMMITTED`). Parallel requests, tabs and application instances
are serialized there, so limits cannot be overshot. No Redis is needed; the lock is held for a
few milliseconds and the expected traffic is low.
- An `IN_PROGRESS` row only blocks new requests (concurrency check) for
`APP_ASSISTANT_STREAM_TIMEOUT + 30s`. If an instance crashes mid-stream, the user is unblocked
after that lease, but the message stays charged.
- Timestamps are stored in UTC; the reset zone is only used to compute day boundaries.

## Accounting policy

| Outcome | Daily user quota | Short window / global limits |
| --- | --- | --- |
| Blocked by a local limit, validation error, assistant disabled | Not charged (no row) | Not counted |
| Local failure after reserving but before the provider call | Not charged (`RELEASED`) | Not counted |
| Completed | Charged (`COMPLETED`) | Counted |
| Provider error before any token was streamed (e.g. provider 429) | Refunded (`REFUNDED`) | Counted, because the provider was called |
| Provider error after tokens were streamed | Charged (`FAILED`) | Counted |
| Client disconnect or SSE timeout | Charged (`CANCELLED`) | Counted |

Refunded failures still count toward the short window, so retry loops are still throttled.

## API contract

Rejected requests get an HTTP `429` JSON response before the SSE stream opens. A generation
that was already authorized is never interrupted by a later rejection.

```json
{
"status": 429,
"error": "Too Many Requests",
"code": "ASSISTANT_DAILY_QUOTA_EXCEEDED",
"message": "Daily assistant message limit reached",
"retryAfterSeconds": 43200,
"retryAt": "2026-11-23T03:00:00Z"
}
```

The `Retry-After` header carries the same seconds when known. Codes:

- `ASSISTANT_DAILY_QUOTA_EXCEEDED`: retry at the next local reset.
- `ASSISTANT_RATE_LIMITED`: retry when the oldest request leaves the short window.
- `ASSISTANT_REQUEST_IN_PROGRESS`: another generation from this user is still running (no `Retry-After`).
- `ASSISTANT_GLOBAL_LIMIT_REACHED`: the shared capacity is exhausted.

Provider rate limits keep the existing SSE `error` event with code `RATE_LIMITED`
(see `AssistantProviderErrorMapper`), which separates local 429s from provider 429s.

`GET /api/v1/assistant/usage` returns only the authenticated user's usage:

```json
{
"quotaEnabled": true,
"dailyLimit": 30,
"used": 4,
"remaining": 26,
"resetAt": "2026-11-23T03:00:00Z",
"resetTimezone": "America/Sao_Paulo"
}
```

`dailyLimit` and `remaining` are `null` when the daily limit is disabled.

## Observability

Prompts are never logged. Metrics (Micrometer, exposed via Prometheus):

- `assistant.quota.decisions{result=allowed|daily_quota|rate_limited|concurrent_request|global_limit}`
- `assistant.requests.in_flight` (per instance gauge)
- `assistant.requests.completed{result=success|failure|cancelled}`
- `assistant.quota.reservations.finished{status=...}`
- `assistant.provider.errors{code=RATE_LIMITED|PROVIDER_UNAVAILABLE}` (provider-side 429 vs other failures)
- `assistant.tokens{type=prompt|completion}` and `assistant.tool.calls`

Token usage comes from Spring AI's `ChatResponse` metadata. It is cumulative across tool-call
rounds for OpenRouter (OpenAI adapter, `stream_options.include_usage` is on by default) and
Gemini. It is also stored per request in `prompt_tokens` / `completion_tokens`. Providers that
report no usage leave those columns `NULL`.

The log event `ASSISTANT_QUOTA_REJECTED` records the reason, user ID and retry delay.
50 changes: 50 additions & 0 deletions src/main/java/com/jobtracker/config/AssistantProperties.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.ZoneId;

@Component
@ConfigurationProperties(prefix = "app.assistant")
Expand All @@ -13,6 +14,9 @@ public class AssistantProperties {
private int maxSearchResults = 20;
private int memoryMaxMessages = 20;
private Duration streamTimeout = Duration.ofSeconds(60);
private int maxOutputTokens = 1024;
private int maxToolCalls = 8;
private final Quota quota = new Quota();

public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
Expand All @@ -26,9 +30,55 @@ public class AssistantProperties {
public void setMemoryMaxMessages(int value) { this.memoryMaxMessages = value; }
public Duration getStreamTimeout() { return streamTimeout; }
public void setStreamTimeout(Duration value) { this.streamTimeout = value; }
public int getMaxOutputTokens() { return maxOutputTokens; }
public void setMaxOutputTokens(int value) { this.maxOutputTokens = value; }
public int getMaxToolCalls() { return maxToolCalls; }
public void setMaxToolCalls(int value) { this.maxToolCalls = value; }
public Quota getQuota() { return quota; }

public int clampLimit(Integer requested) {
int value = requested == null ? defaultSearchResults : requested;
return Math.max(1, Math.min(value, maxSearchResults));
}

/**
* Provider-agnostic usage limits enforced before any ChatModel call.
* A limit of 0 disables that specific check.
*/
public static class Quota {
private boolean enabled = true;
private int dailyLimit = 30;
private ZoneId resetZone = ZoneId.of("America/Sao_Paulo");
private int rateLimit = 5;
private Duration rateWindow = Duration.ofMinutes(1);
private int maxConcurrent = 1;
private int globalDailyLimit = 500;
private int globalRateLimit = 20;
private Duration globalRateWindow = Duration.ofMinutes(1);
private Duration inFlightLeaseMargin = Duration.ofSeconds(30);
private Duration retention = Duration.ofDays(7);

public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
public int getDailyLimit() { return dailyLimit; }
public void setDailyLimit(int value) { this.dailyLimit = value; }
public ZoneId getResetZone() { return resetZone; }
public void setResetZone(ZoneId value) { this.resetZone = value; }
public int getRateLimit() { return rateLimit; }
public void setRateLimit(int value) { this.rateLimit = value; }
public Duration getRateWindow() { return rateWindow; }
public void setRateWindow(Duration value) { this.rateWindow = value; }
public int getMaxConcurrent() { return maxConcurrent; }
public void setMaxConcurrent(int value) { this.maxConcurrent = value; }
public int getGlobalDailyLimit() { return globalDailyLimit; }
public void setGlobalDailyLimit(int value) { this.globalDailyLimit = value; }
public int getGlobalRateLimit() { return globalRateLimit; }
public void setGlobalRateLimit(int value) { this.globalRateLimit = value; }
public Duration getGlobalRateWindow() { return globalRateWindow; }
public void setGlobalRateWindow(Duration value) { this.globalRateWindow = value; }
public Duration getInFlightLeaseMargin() { return inFlightLeaseMargin; }
public void setInFlightLeaseMargin(Duration value) { this.inFlightLeaseMargin = value; }
public Duration getRetention() { return retention; }
public void setRetention(Duration value) { this.retention = value; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.jobtracker.config.AssistantProperties;
import com.jobtracker.dto.assistant.AssistantChatRequest;
import com.jobtracker.dto.assistant.AssistantUsageResponse;
import com.jobtracker.service.assistant.AssistantProviderErrorMapper;
import com.jobtracker.service.assistant.AssistantService;
import com.jobtracker.service.assistant.AssistantService.AssistantStream;
Expand Down Expand Up @@ -56,6 +57,12 @@ public SseEmitter chat(@Valid @RequestBody AssistantChatRequest request) {
return emitter;
}

@PreAuthorize("hasRole('USER') or hasAuthority('SCOPE_read:applications')")
@GetMapping(value = "/usage", produces = MediaType.APPLICATION_JSON_VALUE)
public AssistantUsageResponse usage() {
return assistant.usage();
}

private void send(SseEmitter emitter, String event, Object data) {
try {
emitter.send(SseEmitter.event().name(event).data(data));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.jobtracker.dto.assistant;

import java.time.Instant;

/** dailyLimit and remaining are null when the daily quota is disabled. */
public record AssistantUsageResponse(
boolean quotaEnabled,
Integer dailyLimit,
long used,
Integer remaining,
Instant resetAt,
String resetTimezone
) {}
23 changes: 23 additions & 0 deletions src/main/java/com/jobtracker/entity/AssistantQuotaLock.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.jobtracker.entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

/** Single-row mutex: reservations lock it FOR UPDATE so checks and inserts are atomic across instances. */
@Entity
@Table(name = "assistant_quota_locks")
public class AssistantQuotaLock {
public static final String GLOBAL = "assistant-global";

@Id
@Column(name = "lock_name", length = 64, nullable = false)
private String name;

protected AssistantQuotaLock() {}

public AssistantQuotaLock(String name) { this.name = name; }

public String getName() { return name; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.jobtracker.entity;

import com.jobtracker.entity.enums.AssistantReservationStatus;
import jakarta.persistence.*;
import org.hibernate.annotations.UuidGenerator;

import java.time.LocalDateTime;
import java.util.UUID;

/** Timestamps are stored as UTC wall-clock values, independent of the JVM time zone. */
@Entity
@Table(name = "assistant_request_reservations", indexes = {
@Index(name = "idx_assistant_reservations_user_created", columnList = "user_id, created_at"),
@Index(name = "idx_assistant_reservations_created", columnList = "created_at")
})
public class AssistantRequestReservation {

@Id
@UuidGenerator(style = UuidGenerator.Style.TIME)
@Column(name = "id", columnDefinition = "BINARY(16)", updatable = false, nullable = false)
private UUID id;

@Column(name = "user_id", columnDefinition = "BINARY(16)", nullable = false, updatable = false)
private UUID userId;

@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false, length = 20)
private AssistantReservationStatus status;

@Column(name = "created_at", nullable = false, updatable = false)
private LocalDateTime createdAt;

@Column(name = "finished_at")
private LocalDateTime finishedAt;

@Column(name = "prompt_tokens")
private Integer promptTokens;

@Column(name = "completion_tokens")
private Integer completionTokens;

protected AssistantRequestReservation() {}

public AssistantRequestReservation(UUID userId, LocalDateTime createdAtUtc) {
this.userId = userId;
this.createdAt = createdAtUtc;
this.status = AssistantReservationStatus.IN_PROGRESS;
}

public UUID getId() { return id; }
public UUID getUserId() { return userId; }
public AssistantReservationStatus getStatus() { return status; }
public LocalDateTime getCreatedAt() { return createdAt; }
public LocalDateTime getFinishedAt() { return finishedAt; }
public Integer getPromptTokens() { return promptTokens; }
public Integer getCompletionTokens() { return completionTokens; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.jobtracker.entity.enums;

import java.util.EnumSet;
import java.util.Set;

/**
* Lifecycle of one Ask ApplyWell request slot.
* <ul>
* <li>IN_PROGRESS: authorized, generation running (counts as in flight while the lease is valid).</li>
* <li>COMPLETED / CANCELLED / FAILED: the provider was reached and produced or may have produced output; charged.</li>
* <li>REFUNDED: the provider failed before emitting any output; not charged to the user's daily quota,
* but still counts toward rate windows and global limits because the provider was called.</li>
* <li>RELEASED: the request failed before the provider was called; counts nowhere.</li>
* </ul>
*/
public enum AssistantReservationStatus {
IN_PROGRESS,
COMPLETED,
CANCELLED,
FAILED,
REFUNDED,
RELEASED;

public static final Set<AssistantReservationStatus> CHARGED =
EnumSet.of(IN_PROGRESS, COMPLETED, CANCELLED, FAILED);
public static final Set<AssistantReservationStatus> PROVIDER_REACHED =
EnumSet.of(IN_PROGRESS, COMPLETED, CANCELLED, FAILED, REFUNDED);
}
Loading
Loading