Skip to content

Commit 994da09

Browse files
fix(settings): seed an indexed write from the defaults, not the pre-batch settings
An array is only seeded when the working settings lack it, and there the effective array is the default one. Reading it from the merged settings brought back an override an earlier change in the same batch had removed: stored `pubkey.blacklist = [A, B]`, a batch of `pubkey = {}` then `blacklist[0] = C` saved `[C, B]` where the two requests sent separately save `[C]`. Both passes and the CLI now pass `loadDefaults()`, which is the same object a single change saw before (`merged` equals defaults whenever the settings do not hold the key) and the right one mid-batch. Raised by CodeRabbit on #1279.
1 parent 6fe9805 commit 994da09

4 files changed

Lines changed: 50 additions & 20 deletions

File tree

‎src/cli/commands/config.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import yaml from 'js-yaml'
33

44
import {
55
getByPath,
6+
loadDefaults,
67
loadMergedSettings,
78
loadUserSettings,
89
parseTypedValue,
@@ -138,8 +139,8 @@ export const runConfigSet = async (
138139
>(() => {
139140
const settings = loadUserSettings() as unknown as Record<string, unknown>
140141
const merged = loadMergedSettings() as unknown as Record<string, unknown>
141-
// With the merged settings, writing one field of a default array keeps the rest of that array.
142-
const next = setByPath(settings, path, parseTypedValue(rawValue, valueType), merged)
142+
// With the defaults, writing one field of a default array keeps the rest of that array.
143+
const next = setByPath(settings, path, parseTypedValue(rawValue, valueType), loadDefaults() as any)
143144

144145
if (options.validate !== false) {
145146
const mergedNext = setByPath(merged, path, getByPath(next, path))

‎src/controllers/admin/patch-settings-controller.ts‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { adminSettingsPatchBodySchema } from '../../schemas/admin-settings-schem
66
import {
77
appendSettingsAuditLog,
88
getByPath,
9+
loadDefaults,
910
loadMergedSettings,
1011
loadUserSettings,
1112
saveSettings,
@@ -62,6 +63,10 @@ export class PatchAdminSettingsController implements IController {
6263
>(() => {
6364
const userSettings = loadUserSettings() as unknown as Record<string, unknown>
6465
const merged = loadMergedSettings() as unknown as Record<string, unknown>
66+
// The seed for an indexed write. Only a key the working settings lack is seeded, so the effective
67+
// array there is the default one: reading it from `merged` (the pre-batch settings) would bring back
68+
// an override an earlier change in the same batch removed.
69+
const defaults = loadDefaults() as unknown as Record<string, unknown>
6570
// Taken before the changes are applied, in case applying them edits this object in place.
6671
const protectedBefore = JSON.parse(JSON.stringify(userSettings)) as Record<string, unknown>
6772
let nextUserSettings: Record<string, unknown>
@@ -70,9 +75,9 @@ export class PatchAdminSettingsController implements IController {
7075
// settings would replay change 3 before change 2 and fail on a batch whose final settings are valid.
7176
const applied: unknown[] = []
7277
try {
73-
// With the merged settings, writing one field of a default array keeps the rest of that array.
78+
// With the defaults, writing one field of a default array keeps the rest of that array.
7479
nextUserSettings = changes.reduce((settings, change) => {
75-
const next = setByPath(settings, change.path, change.value, merged)
80+
const next = setByPath(settings, change.path, change.value, defaults)
7681
applied.push(getByPath(next, change.path))
7782
return next
7883
}, userSettings)
@@ -94,14 +99,14 @@ export class PatchAdminSettingsController implements IController {
9499
}
95100
}
96101

97-
// The replay runs the same writes in the same order onto the merged settings, whose arrays are at least
98-
// as long as the stored ones at every step, so it can only fail where the first pass already did.
102+
// The replay runs the same writes in the same order onto the merged settings, with the same seed the
103+
// first pass used, so it can only fail where the first pass already did.
99104
let mergedNext: Record<string, unknown>
100105
try {
101-
// The seed is the same `merged`, as in the first pass: a replay of `limits.event = {}` leaves
102-
// an array an earlier default carried to be copied again, not started empty.
106+
// The seed is the same `defaults`, as in the first pass: a replay of `limits.event = {}` copies
107+
// the default array again rather than starting it empty.
103108
mergedNext = changes.reduce(
104-
(settings, change, index) => setByPath(settings, change.path, applied[index], merged),
109+
(settings, change, index) => setByPath(settings, change.path, applied[index], defaults),
105110
merged,
106111
)
107112
} catch (error) {

‎src/utils/settings-config.ts‎

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -767,16 +767,17 @@ const assertWritableIndex = (target: unknown[], index: number, path: string): vo
767767
/**
768768
* Returns a copy of `settings` with `value` written at `path`.
769769
*
770-
* An array in settings.yaml replaces the default array as a whole. When `effective` (the defaults merged with
771-
* `settings`) is given, an indexed write into an array that `settings` does not hold yet starts from a copy of the
772-
* effective array. So `limits.event.content[1].maxLength` changes that one field and keeps the other entries and
773-
* fields, instead of saving an array that holds only the field that was written.
770+
* An array in settings.yaml replaces the default array as a whole. When `defaults` is given, an indexed write into
771+
* an array that `settings` does not hold yet starts from a copy of the default array there. So
772+
* `limits.event.content[1].maxLength` changes that one field and keeps the other entries and fields, instead of
773+
* saving an array that holds only the field that was written. Pass the defaults, not the merged settings: a batch
774+
* can remove an override before writing into the array, and the merged settings still carry it.
774775
*/
775776
export const setByPath = (
776777
settings: Record<string, unknown>,
777778
path: string,
778779
value: unknown,
779-
effective?: Record<string, unknown>,
780+
defaults?: Record<string, unknown>,
780781
): Record<string, unknown> => {
781782
const tokens = parsePath(path)
782783
const clone: Record<string, unknown> = structuredClone(settings)
@@ -786,7 +787,7 @@ export const setByPath = (
786787
}
787788

788789
let current: unknown = clone
789-
let currentEffective: unknown = effective
790+
let currentDefaults: unknown = defaults
790791

791792
for (let i = 0; i < tokens.length - 1; i++) {
792793
const token = tokens[i]
@@ -798,11 +799,11 @@ export const setByPath = (
798799
}
799800

800801
const existing = current[token.key]
801-
const effectiveChild =
802-
isPlainObject(currentEffective) && hasOwn(currentEffective, token.key) ? currentEffective[token.key] : undefined
802+
const defaultChild =
803+
isPlainObject(currentDefaults) && hasOwn(currentDefaults, token.key) ? currentDefaults[token.key] : undefined
803804
if (existing === undefined) {
804805
if (nextToken.type === 'index') {
805-
current[token.key] = Array.isArray(effectiveChild) ? structuredClone(effectiveChild) : []
806+
current[token.key] = Array.isArray(defaultChild) ? structuredClone(defaultChild) : []
806807
} else {
807808
current[token.key] = {}
808809
}
@@ -813,7 +814,7 @@ export const setByPath = (
813814
}
814815

815816
current = current[token.key]
816-
currentEffective = effectiveChild
817+
currentDefaults = defaultChild
817818
continue
818819
}
819820

@@ -833,7 +834,7 @@ export const setByPath = (
833834
}
834835

835836
current = current[token.index]
836-
currentEffective = Array.isArray(currentEffective) ? currentEffective[token.index] : undefined
837+
currentDefaults = Array.isArray(currentDefaults) ? currentDefaults[token.index] : undefined
837838
}
838839

839840
const last = tokens[tokens.length - 1]

‎test/unit/controllers/admin/patch-settings-controller.spec.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ describe('PatchAdminSettingsController settings write lock', () => {
3636
sandbox.stub(settingsConfig, 'withSettingsWriteLock').callsFake(async (operation: () => unknown) => operation())
3737
sandbox.stub(settingsConfig, 'loadUserSettings').returns(baseSettings as any)
3838
sandbox.stub(settingsConfig, 'loadMergedSettings').returns(baseSettings as any)
39+
sandbox.stub(settingsConfig, 'loadDefaults').returns(baseSettings as any)
3940
sandbox.stub(settingsConfig, 'saveSettings')
4041
sandbox.stub(settingsConfig, 'appendSettingsAuditLog')
4142
sandbox.stub(settingsConfig, 'validatePathAgainstDefaults').returns([])
@@ -170,6 +171,7 @@ describe('PatchAdminSettingsController settings write lock', () => {
170171
{ description: 'kinds 11-39', maxLength: 200, kinds: [[11, 39]] },
171172
]
172173
;(settingsConfig.loadMergedSettings as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { content } } })
174+
;(settingsConfig.loadDefaults as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { content } } })
173175
request.body = { path: 'limits.event.content[1].maxLength', value: 500 }
174176

175177
const controller = new PatchAdminSettingsController(outboxRepository as any)
@@ -206,6 +208,7 @@ describe('PatchAdminSettingsController settings write lock', () => {
206208
{ description: 'kinds 11-39', maxLength: 200, kinds: [[11, 39]] },
207209
]
208210
;(settingsConfig.loadMergedSettings as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { content } } })
211+
;(settingsConfig.loadDefaults as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { content } } })
209212
request.body = {
210213
changes: [
211214
{ path: 'limits.event', value: {} },
@@ -221,6 +224,26 @@ describe('PatchAdminSettingsController settings write lock', () => {
221224
expect(saved.limits.event.content).to.deep.equal([content[0], { ...content[1], maxLength: 500 }])
222225
})
223226

227+
it('does not bring back a stored override an earlier change in the batch removed', async () => {
228+
const stored = { blacklist: ['a.example', 'b.example'] }
229+
;(settingsConfig.loadUserSettings as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { pubkey: stored } } })
230+
;(settingsConfig.loadMergedSettings as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { pubkey: stored } } })
231+
;(settingsConfig.loadDefaults as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { pubkey: { blacklist: [] } } } })
232+
request.body = {
233+
changes: [
234+
{ path: 'limits.event.pubkey', value: {} },
235+
{ path: 'limits.event.pubkey.blacklist[0]', value: 'c.example' },
236+
],
237+
}
238+
239+
const controller = new PatchAdminSettingsController(outboxRepository as any)
240+
await controller.handleRequest(request as any, response as any)
241+
242+
expect(response.status).to.have.been.calledOnceWithExactly(200)
243+
const saved = (settingsConfig.saveSettings as Sinon.SinonStub).firstCall.args[0]
244+
expect(saved.limits.event.pubkey.blacklist).to.deep.equal(['c.example'])
245+
})
246+
224247
it('reports an unappliable batch as a path issue instead of a 500', async () => {
225248
request.body = {
226249
changes: [

0 commit comments

Comments
 (0)