> ## Documentation Index
> Fetch the complete documentation index at: https://docs.internal.nscale.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Reassign device rack slots atomically

> Move devices to new rack slots as one unit, so they can cross over.

The single-device update path cannot express a swap. `(rack, position)` is
unique, so whichever of the two devices moves first lands on the other — there is
no ordering that avoids it, and the netbox agent consequently deadlocked on every
tray swap and served the pre-swap location indefinitely.

This applies the whole batch in one transaction, with the constraint DEFERRED so
it is judged once at COMMIT rather than per row. `QuerySet.update()` is used
deliberately: `full_clean` would reject the intermediate overlap in Python before
the database ever saw it (`BaseModel.validate_constraints` refuses to exclude
fields, by design), so nothing outside the transaction observes the crossing.

Bypassing `full_clean` means the invariants it would have applied are the
serializer's job instead: it derives `location`/`site` from the target rack (they
are non-editable and normally re-derived by `Device.save()`) and rejects a batch
that no ordering could satisfy. Only those four columns are written — name, Ironic
reference and status are untouched, because a physical move is all this represents.

The occupancy check covers only `(rack, position)`, not NVSwitch slots. A bad
NVSwitch slot swap therefore fails at commit with HTTP 409. NVSwitch rack moves
are manual in the M1.5 milestone. Revisit this check before automating them in a
later milestone.

Every member is locked in device-id order before anything is written. Two agent
workers reconciling the two halves of one swap concurrently each put their own
device first, which would be a lock cycle and a Postgres deadlock; taking the locks
in a stable order makes the loser wait instead, and it is then a no-op because the
winner already committed the layout it was going to write. The same lock closes the
window in which a member deleted after validation would leave its partner's move
committed on its own — that returns 409 rather than a half-applied swap.



## OpenAPI

````yaml /openapi/fleet-manager-openapi.yaml post /api/v1/devices/reassign-slots/
openapi: 3.0.3
info:
  title: Fleet Manager API
  version: 1.0.0
  description: API for the Nscale Fleet Manager
servers: []
security: []
paths:
  /api/v1/devices/reassign-slots/:
    post:
      tags:
        - Devices
      summary: Reassign device rack slots atomically
      description: >-
        Move devices to new rack slots as one unit, so they can cross over.


        The single-device update path cannot express a swap. `(rack, position)`
        is

        unique, so whichever of the two devices moves first lands on the other —
        there is

        no ordering that avoids it, and the netbox agent consequently deadlocked
        on every

        tray swap and served the pre-swap location indefinitely.


        This applies the whole batch in one transaction, with the constraint
        DEFERRED so

        it is judged once at COMMIT rather than per row. `QuerySet.update()` is
        used

        deliberately: `full_clean` would reject the intermediate overlap in
        Python before

        the database ever saw it (`BaseModel.validate_constraints` refuses to
        exclude

        fields, by design), so nothing outside the transaction observes the
        crossing.


        Bypassing `full_clean` means the invariants it would have applied are
        the

        serializer's job instead: it derives `location`/`site` from the target
        rack (they

        are non-editable and normally re-derived by `Device.save()`) and rejects
        a batch

        that no ordering could satisfy. Only those four columns are written —
        name, Ironic

        reference and status are untouched, because a physical move is all this
        represents.


        The occupancy check covers only `(rack, position)`, not NVSwitch slots.
        A bad

        NVSwitch slot swap therefore fails at commit with HTTP 409. NVSwitch
        rack moves

        are manual in the M1.5 milestone. Revisit this check before automating
        them in a

        later milestone.


        Every member is locked in device-id order before anything is written.
        Two agent

        workers reconciling the two halves of one swap concurrently each put
        their own

        device first, which would be a lock cycle and a Postgres deadlock;
        taking the locks

        in a stable order makes the loser wait instead, and it is then a no-op
        because the

        winner already committed the layout it was going to write. The same lock
        closes the

        window in which a member deleted after validation would leave its
        partner's move

        committed on its own — that returns 409 rather than a half-applied swap.
      operationId: api_v1_devices_reassign_slots_create
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/DeviceReassignSlotsRequest'
          application/x-www-form-urlencoded:
            schema:
              $ref: '#/components/schemas/DeviceReassignSlotsRequest'
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/DeviceReassignSlotsRequest'
        required: true
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DeviceReassignSlotsResponse'
          description: ''
        '400':
          description: Validation error.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Authentication credentials were not provided or are invalid.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: You do not have permission to perform this action.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '409':
          description: >-
            The devices or rack positions changed while the reassignment was
            being applied; re-read the layout and retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      security:
        - oauth2:
            - device:update
        - cookieAuth: []
components:
  schemas:
    DeviceReassignSlotsRequest:
      type: object
      description: >-
        Input payload for the atomic slot reassignment action.


        Every assignment is applied together, so a set that merely *passes
        through* an

        occupied slot — the swap case, where each device wants the other's — is
        legal even

        though no single assignment in it is.


        ``max_length`` documents the intent as much as it bounds the work: the
        netbox agent

        submits one 2-device swap, and each assignment costs its own UPDATE
        inside a single

        transaction holding row locks until COMMIT.
      properties:
        assignments:
          type: array
          items:
            $ref: '#/components/schemas/DeviceSlotAssignment'
          maxItems: 64
          minItems: 1
      required:
        - assignments
    DeviceReassignSlotsResponse:
      type: object
      description: Result of an atomic slot reassignment.
      properties:
        devices_changed:
          type: integer
      required:
        - devices_changed
    ErrorResponse:
      type: object
      description: >-
        Uniform error body for every 4xx/5xx response. `detail` is a
        human-readable message, always present, safe to display to end users.
        `code` is the machine-readable identifier. `field_errors` lists
        per-input-field validation messages and is empty for non-field errors
        (auth, permission, not-found, conflict, server).
      required:
        - detail
        - code
        - field_errors
      properties:
        detail:
          type: string
        code:
          $ref: '#/components/schemas/ErrorCodeEnum'
        field_errors:
          type: array
          items:
            $ref: '#/components/schemas/FieldError'
    DeviceSlotAssignment:
      type: object
      description: One device's target rack slot within a `reassign-slots` request.
      properties:
        device_id:
          type: string
          format: uuid
        rack_id:
          type: string
          format: uuid
        position:
          type: string
          format: decimal
          pattern: ^-?\d{0,3}(?:\.\d{0,1})?$
      required:
        - device_id
        - position
        - rack_id
    ErrorCodeEnum:
      type: string
      description: >-
        Stable machine-readable error identifier. New members may be added
        within this API version; clients must tolerate unknown values.
      enum:
        - error
        - invalid
        - parse_error
        - authentication_failed
        - not_authenticated
        - permission_denied
        - not_found
        - method_not_allowed
        - not_acceptable
        - unsupported_media_type
        - conflict
        - enrollment_infrastructure_reference_pending
        - enrollment_infrastructure_reference_changed
        - unprocessable_entity
        - throttled
        - service_unavailable
    FieldError:
      type: object
      description: One input field's validation messages.
      required:
        - field
        - messages
      properties:
        field:
          type: string
          description: >-
            Dotted path to the offending input field, or to the collection row
            when the whole row is invalid (e.g. `filters.end_date`,
            `memberships.0.role`, `memberships.0`).
        messages:
          type: array
          minItems: 1
          items:
            type: string
  securitySchemes:
    oauth2:
      type: oauth2
      flows: {}
    cookieAuth:
      type: apiKey
      in: cookie
      name: sessionid

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.