📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
fix feature flag scheduling edge cases
Blue Mousef6faeb73e70b
diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts b/backend/apps/cloud/src/feature-flag/feature-flag.controller.tsindex bb05d6895..7f8291c09 100644--- a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts+++ b/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts@@ -141,6 +141,7 @@ export class FeatureFlagController {flag: FeatureFlag,lastEvaluatedAt: string | null,completedExperimentIds: Set<string>,+ skipEvaluationStaleness = false,) {const reasons: FeatureFlagStaleReason[] = []const createdAge = this.getAgeInDays(flag.created)@@ -149,13 +150,18 @@ export class FeatureFlagController {flag.targetingUpdatedAt || flag.created,)- if (!lastEvaluatedAt && createdAge >= FEATURE_FLAG_EVALUATION_STALE_DAYS) {- reasons.push(FeatureFlagStaleReason.NOT_EVALUATED_RECENTLY)- } else if (- lastEvaluatedAt &&- this.getAgeInDays(lastEvaluatedAt) >= FEATURE_FLAG_EVALUATION_STALE_DAYS- ) {- reasons.push(FeatureFlagStaleReason.NOT_EVALUATED_RECENTLY)+ if (!skipEvaluationStaleness) {+ if (+ !lastEvaluatedAt &&+ createdAge >= FEATURE_FLAG_EVALUATION_STALE_DAYS+ ) {+ reasons.push(FeatureFlagStaleReason.NOT_EVALUATED_RECENTLY)+ } else if (+ lastEvaluatedAt &&+ this.getAgeInDays(lastEvaluatedAt) >= FEATURE_FLAG_EVALUATION_STALE_DAYS+ ) {+ reasons.push(FeatureFlagStaleReason.NOT_EVALUATED_RECENTLY)+ }}if (@@ -200,11 +206,19 @@ export class FeatureFlagController {}private async decorateFeatureFlags(projectId: string, flags: FeatureFlag[]) {- const lastEvaluatedAtByFlag =- await this.featureFlagService.getLastEvaluatedAtByFlagIds(- projectId,- flags.map((flag) => flag.id),- )+ let skipEvaluationStaleness = false+ let lastEvaluatedAtByFlag = new Map<string, string>()++ try {+ lastEvaluatedAtByFlag =+ await this.featureFlagService.getLastEvaluatedAtByFlagIds(+ projectId,+ flags.map((flag) => flag.id),+ )+ } catch {+ skipEvaluationStaleness = true+ }+const experimentIds = flags.map((flag) => flag.experimentId).filter((id): id is string => Boolean(id))@@ -231,6 +245,7 @@ export class FeatureFlagController {effectiveFlag,lastEvaluatedAt,completedExperimentIds,+ skipEvaluationStaleness,)return {@@ -720,6 +735,8 @@ export class FeatureFlagController {}}+ await this.featureFlagService.applyDueScheduledChanges(flag.project.id)+this.validateScheduledChange(flagDto.scheduledChange)const updatePayload: Partial<FeatureFlag> = {diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.service.ts b/backend/apps/cloud/src/feature-flag/feature-flag.service.tsindex 10c08f984..edec2cca5 100644--- a/backend/apps/cloud/src/feature-flag/feature-flag.service.ts+++ b/backend/apps/cloud/src/feature-flag/feature-flag.service.ts@@ -10,6 +10,7 @@ import {} from 'typeorm'import { Pagination, PaginationOptionsInterface } from '../common/pagination'import { clickhouse } from '../common/integrations/clickhouse'+import { AppLoggerService } from '../logger/logger.service'import { FeatureFlag } from './entity/feature-flag.entity'import {evaluateFlag as sharedEvaluateFlag,@@ -22,6 +23,7 @@ export class FeatureFlagService {constructor(@InjectRepository(FeatureFlag)private featureFlagRepository: Repository<FeatureFlag>,+ private readonly logger: AppLoggerService,) {}async paginate(@@ -135,20 +137,24 @@ export class FeatureFlagService {`try {- const { data } = await clickhouse- .query({- query,- query_params: { pid: projectId, flagIds },- })- .then((resultSet) =>- resultSet.json<{ flagId: string; lastEvaluatedAt: string }>(),- )+ const resultSet = await clickhouse.query({+ query,+ query_params: { pid: projectId, flagIds },+ })+ const { data } = await resultSet.json<{+ flagId: string+ lastEvaluatedAt: string+ }>()for (const row of data) {result.set(row.flagId, row.lastEvaluatedAt)}- } catch {- return result+ } catch (err) {+ this.logger.error(+ { err, projectId, flagIds },+ 'Failed to get feature flag evaluation timestamps',+ )+ throw err}return resultdiff --git a/backend/apps/community/src/feature-flag/feature-flag.controller.ts b/backend/apps/community/src/feature-flag/feature-flag.controller.tsindex 5088883ec..0fc34bb77 100644--- a/backend/apps/community/src/feature-flag/feature-flag.controller.ts+++ b/backend/apps/community/src/feature-flag/feature-flag.controller.ts@@ -668,6 +668,8 @@ export class FeatureFlagController {}}+ await this.featureFlagService.applyDueScheduledChanges(flag.projectId)+this.validateScheduledChange(flagDto.scheduledChange)const updatePayload: Partial<FeatureFlag> = {diff --git a/backend/migrations/clickhouse/selfhosted_2026_05_24_feature_flag_operations.js b/backend/migrations/clickhouse/selfhosted_2026_05_24_feature_flag_operations.jsindex 1d5ca1902..0924624a5 100644--- a/backend/migrations/clickhouse/selfhosted_2026_05_24_feature_flag_operations.js+++ b/backend/migrations/clickhouse/selfhosted_2026_05_24_feature_flag_operations.js@@ -1,7 +1,7 @@const { queriesRunner, dbName } = require('./setup')const queries = [- `ALTER TABLE ${dbName}.feature_flag ADD COLUMN IF NOT EXISTS scheduledChange Nullable(String) AFTER experimentId;`,+ `ALTER TABLE ${dbName}.feature_flag ADD COLUMN IF NOT EXISTS scheduledChange Nullable(String);`,`ALTER TABLE ${dbName}.feature_flag ADD COLUMN IF NOT EXISTS killSwitchActive Int8 DEFAULT 0 AFTER scheduledChange;`,`ALTER TABLE ${dbName}.feature_flag ADD COLUMN IF NOT EXISTS killSwitchValue Int8 DEFAULT 0 AFTER killSwitchActive;`,`ALTER TABLE ${dbName}.feature_flag ADD COLUMN IF NOT EXISTS killedAt Nullable(DateTime('UTC')) AFTER killSwitchValue;`,diff --git a/web/app/components/ToolsNav.tsx b/web/app/components/ToolsNav.tsxindex 1ef9944ac..3e032e342 100644--- a/web/app/components/ToolsNav.tsx+++ b/web/app/components/ToolsNav.tsx@@ -320,7 +320,7 @@ export function ToolsNav({ className }: ToolsNavProps) {key={tool.id}to={tool.href}className={cn(- 'flex items-start gap-3 px-3 py-2 transition-colors',+ 'flex items-start gap-3 px-4 py-3 transition-colors',index !== 0 && 'border-t border-gray-100 dark:border-slate-800',isActive? 'bg-gray-50 dark:bg-slate-800/50'@@ -377,7 +377,7 @@ export function ToolsNavMobile({ className }: ToolsNavProps) {<buttontype='button'onClick={() => setIsOpen(!isOpen)}- className='flex w-full items-center justify-between gap-3 px-3 py-2'+ className='flex w-full items-center justify-between gap-3 px-4 py-3'><div className='flex items-center gap-3'>{CurrentIcon && (diff --git a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsx b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsxindex 8722e79c4..048d2db79 100644--- a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsx+++ b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsx@@ -742,7 +742,9 @@ const flags = await swetrix.getFeatureFlags(undefined, true)`type='datetime-local'label={t('featureFlags.scheduleAt')}value={scheduledApplyAt}- min={dayjs().format('YYYY-MM-DDTHH:mm')}+ min={dayjs()+ .add(1, 'minute')+ .format('YYYY-MM-DDTHH:mm')}onChange={(e) =>setScheduledApplyAt(e.target.value)}diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsxindex 37e1e54aa..b7541b62b 100644--- a/web/app/routes/projects.$id.tsx+++ b/web/app/routes/projects.$id.tsx@@ -1736,9 +1736,18 @@ export async function action({ request, params }: ActionFunctionArgs) {)const enabled = formData.get('enabled') === 'true'const scheduledChangeRaw = formData.get('scheduledChange')?.toString()- const scheduledChange = scheduledChangeRaw- ? JSON.parse(scheduledChangeRaw)- : null+ let scheduledChange: unknown = null++ if (scheduledChangeRaw) {+ try {+ scheduledChange = JSON.parse(scheduledChangeRaw)+ } catch {+ return data<ProjectViewActionData>(+ { intent, error: 'Invalid JSON in scheduledChange' },+ { status: 400 },+ )+ }+ }const result = await serverFetch(request, 'feature-flag', {method: 'POST',@@ -1781,11 +1790,24 @@ export async function action({ request, params }: ActionFunctionArgs) {const enabled = formData.has('enabled')? formData.get('enabled') === 'true': undefined- const scheduledChange = formData.has('scheduledChange')- ? formData.get('scheduledChange')?.toString() === 'null'- ? null- : JSON.parse(formData.get('scheduledChange')!.toString())- : undefined+ let scheduledChange: unknown = undefined++ if (formData.has('scheduledChange')) {+ const scheduledChangeRaw = formData.get('scheduledChange')?.toString()++ if (scheduledChangeRaw === 'null') {+ scheduledChange = null+ } else {+ try {+ scheduledChange = JSON.parse(scheduledChangeRaw || '')+ } catch {+ return data<ProjectViewActionData>(+ { intent, error: 'Invalid JSON in scheduledChange' },+ { status: 400 },+ )+ }+ }+ }const body: Record<string, unknown> = {}if (key !== undefined) body.key = key@@ -1817,7 +1839,16 @@ export async function action({ request, params }: ActionFunctionArgs) {case 'kill-feature-flag': {const flagId = formData.get('flagId')?.toString()- const killSwitchValue = formData.get('killSwitchValue') === 'true'+ const rawKillSwitch = formData.get('killSwitchValue')?.toString()++ if (rawKillSwitch !== 'true' && rawKillSwitch !== 'false') {+ return data<ProjectViewActionData>(+ { intent, error: 'Invalid killSwitchValue' },+ { status: 400 },+ )+ }++ const killSwitchValue = rawKillSwitch === 'true'const result = await serverFetch(request, `feature-flag/${flagId}/kill`, {method: 'PUT',